Python에서 셸 명령 실행

Python에서 셸 명령 실행

환경-PyCharm

JSON 파일을 얻으려면 다음 명령을 사용하고 있습니다.

aws rds describe-db-cluster-snapshots > snapshotdetails.json

일부 데이터를 추출하기 위해 이 Json 파일을 사용하고 있습니다. 내 Python 스크립트에서 위 명령을 실행하고 싶습니다. 나는 다음을 시도했지만 실패했습니다.

from subprocess import call
call(["aws rds describe-db-cluster-snapshots > snapshotdetails.json"])

오류가 발생하고 작동하지 않습니다. 어떤 충고? ?

실수:-

Traceback (most recent call last):File "/Users/PrashastKumar/Desktop/CrossRegion/venv/lib/crossregiontrial.py", line 3, in <module>
call(["aws rds describe-db-cluster-snapshots > snapshotdetails.txt"])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

답변1

일방 python3통행:

from subprocess import Popen, PIPE
cmd_output = Popen(["echo", "foo"], stdout=PIPE)
with open('bar.txt', 'w') as out_handle:
    out_handle.write(cmd_output.communicate()[0].decode('UTF-8'))

관련 정보