subprocess
そのためのモジュールを調べる必要があります。check_call
終了コードを調べる方法があります(これは1つの方法であり、他の方法もあります)。マニュアルに記載されているように:
引数を指定してコマンドを実行します。コマンドが完了するのを待ちます。戻りコードがゼロの場合は戻り、そうでない場合はCalledProcessErrorを発生させます。CalledProcessErrorオブジェクトは、returncode属性に戻りコードを持ちます
この例は次のとおりです。
import subprocess
command=["ls", "-l"]
try:
exit_code=subprocess.check_call(command)
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
これには出力も含まれ、ファイルにリダイレクトするか、次のように抑制することができます。
import subprocess
import os
command=["ls", "-l"]
try:
exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
ゼロ以外の終了コードを使用した呼び出しの例を次に示します。
import subprocess
import os
command=["grep", "mystring", "/home/cwgem/testdir/test.txt"]
try:
exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
出力:
$ python process_exitcode_test.py
Program exited with exit code 1
これは、上記のように処理できる例外としてキャプチャされます。これは、アクセスが拒否された、ファイルが見つからないなどの例外を処理しないことに注意してください。自分で処理する必要があります。