前に説明したように、サブプロセスモジュールを使用できます(使用する必要があります) 。
デフォルトでは、shell
パラメータはFalse
です。これは良いことで、とても安全です。また、フルパスを渡す必要はありません。実行可能ファイル名と引数をシーケンス(タプルまたはリスト)として渡すだけです。
import subprocess
# This works fine
p = subprocess.Popen(["echo","2"])
# These will raise OSError exception:
p = subprocess.Popen("echo 2")
p = subprocess.Popen(["echo 2"])
p = subprocess.Popen(["echa", "2"])
サブプロセスモジュールですでに定義されている次の2つの便利な関数を使用することもできます。
# Their arguments are the same as the Popen constructor
retcode = subprocess.call(["echo", "2"])
subprocess.check_call(["echo", "2"])
stdout
リダイレクトおよび/またはstderr
にリダイレクトできるPIPE
ため、画面に出力されないことを忘れないでください(ただし、出力はPythonプログラムで読み取ることができます)。デフォルトでは、stdout
とstderr
は両方ともですNone
。これは、リダイレクトがないことを意味します。つまり、Pythonプログラムと同じstdout/stderrを使用します。
また、を使用shell=True
してリダイレクトすることもできますstdout
。stderr
PIPEに送信されるため、メッセージは出力されません。
# This will work fine, but no output will be printed
p = subprocess.Popen("echo 2", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# This will NOT raise an exception, and the shell error message is redirected to PIPE
p = subprocess.Popen("echa 2", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)