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'))

おすすめ記事