Python subprocess.run()の使い方|戻り値・capture_output・check・shell・timeoutを実行結果で解説
Pythonで外部コマンドを実行するなら、subprocess.run(["コマンド", "引数"], capture_output=True, text=True, check=True)が基本形です。戻り値のCompletedProcessからreturncode・stdout・stderrを取り出せます。
Python公式ドキュメントも「処理できる用途ではすべてrun()を使うのが推奨。より高度な用途ではPopenを直接使う」としています。この記事では、引数ごとの動きと、つまずきやすい点(bytesになる、失敗しても止まらない、shell=Trueの危険、Windowsとの違い)を、実際に実行した結果つきで説明します。実行環境はPython 3.12.15(macOS)、参照した公式ドキュメントはPython 3.15.0版です(2026年10月18日確認)。
subprocess.run()の基本の書き方と戻り値
import subprocess
r = subprocess.run(["echo", "hello"])
print("returncode:", r.returncode)
print("type:", type(r).__name__)
実行結果:
hello
returncode: 0
type: CompletedProcess
コマンドと引数はリストで渡します。run()はコマンドが終わるまで待ち、CompletedProcessオブジェクトを返します。この例では出力を受け取っていないので、helloは画面にそのまま流れています。
r = subprocess.run(["echo", "x"], capture_output=True, text=True)
print(r)
実行結果:
CompletedProcess(args=['echo', 'x'], returncode=0, stdout='x\n', stderr='')
| 属性・メソッド | 中身 |
|---|---|
args |
実行したコマンド |
returncode |
終了コード(0が成功、0以外は失敗) |
stdout |
標準出力(受け取る設定のときだけ。ないときはNone) |
stderr |
標準エラー出力(同上) |
check_returncode() |
終了コードが0以外ならCalledProcessErrorを出す |
出力を文字列で受け取る|capture_outputとtext
import subprocess
r = subprocess.run(["echo", "hello"], capture_output=True, text=True)
print("stdout:", repr(r.stdout))
print("stderr:", repr(r.stderr))
print("returncode:", r.returncode)
実行結果:
stdout: 'hello\n'
stderr: ''
returncode: 0
capture_output=Trueがないと、出力は画面に流れるだけで変数に入りません。末尾の改行が気になるときはr.stdout.strip()で取り除きます。
text=Trueを忘れるとbytesになる
r = subprocess.run(["echo", "hello"], capture_output=True)
print(repr(r.stdout))
実行結果:
b'hello\n'
先頭にbが付いたバイト列です。r.stdout == "hello\n"がFalseになる、という定番のつまずきです。文字列で扱うならtext=Trueを付けます。文字化けするときはencoding="utf-8"(Windowsで日本語を出すコマンドならencoding="cp932"など、コマンドが出す文字コード)を指定してください。textとcapture_outputはPython 3.7で追加された引数で、それより古いコードではuniversal_newlines=Trueとstdout=subprocess.PIPEで同じことをしています。
標準出力とエラー出力をまとめる・捨てる
公式ドキュメントのとおり、capture_outputとstdout・stderrは同時に指定できません。エラー出力も同じ文字列にまとめたいときは次のように書きます。
r = subprocess.run(["ls", "keep.txt", "/no/such"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
print(repr(r.stdout))
実行結果:
'ls: /no/such: No such file or directory\nkeep.txt\n'
出力が不要ならsubprocess.DEVNULLに捨てられます。
r = subprocess.run(["ls", "/no/such"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print(r.returncode)
実行結果:
1
失敗しても例外にならない|checkで止める
r = subprocess.run(["ls", "/no/such/dir"], capture_output=True, text=True)
print("returncode:", r.returncode)
print("stderr:", repr(r.stderr))
実行結果:
returncode: 1
stderr: 'ls: /no/such/dir: No such file or directory\n'
コマンドが失敗しても、Pythonのプログラムは何事もなかったように次へ進みます。returncodeを見ない限り、失敗に気づけません。
try:
subprocess.run(["ls", "/no/such/dir"],
capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
print(type(e).__name__ + ":", e)
print(" returncode:", e.returncode)
print(" stderr:", repr(e.stderr))
実行結果:
CalledProcessError: Command '['ls', '/no/such/dir']' returned non-zero exit status 1.
returncode: 1
stderr: 'ls: /no/such/dir: No such file or directory\n'
check=Trueを付けると、終了コードが0以外のときCalledProcessErrorが出ます。例外オブジェクトから終了コードと出力も取れます。このエラーメッセージ(returned non-zero exit status)の読み方はsubprocess.CalledProcessErrorの解説で詳しく扱っています。
発生する例外は3種類
try:
subprocess.run(["nosuchcmd_xyz"])
except FileNotFoundError as e:
print(type(e).__name__ + ":", e)
実行結果:
FileNotFoundError: [Errno 2] No such file or directory: 'nosuchcmd_xyz'
| 状況 | 発生する例外 | check=Trueが必要か |
|---|---|---|
| コマンドが見つからない | FileNotFoundError |
不要(常に出る) |
| コマンドが0以外で終了した | CalledProcessError |
必要 |
timeoutの時間を超えた |
TimeoutExpired |
不要 |
timeoutで止まらないコマンドを打ち切る
try:
subprocess.run(["sleep", "5"], timeout=0.5)
except subprocess.TimeoutExpired as e:
print(type(e).__name__ + ":", e)
実行結果:
TimeoutExpired: Command '['sleep', '5']' timed out after 0.4999769589994685 seconds
時間を超えると子プロセスは終了させられ、TimeoutExpiredが出ます。応答しないネットワークコマンドなどでプログラム全体が固まるのを防げるので、自動で動かす処理では付けておくのが安全です。
コマンドはリストで渡す|shell=Trueとの違い
try:
subprocess.run("echo hello")
except FileNotFoundError as e:
print(type(e).__name__ + ":", e)
実行結果:
FileNotFoundError: [Errno 2] No such file or directory: 'echo hello'
macOSやLinuxで文字列をそのまま渡すと、「echo hello」という名前のコマンドを探しに行きます。リストで渡せば、空白を含む引数も1つの引数として正しく渡ります。
r = subprocess.run(["echo", "a b", "c"], capture_output=True, text=True)
print(repr(r.stdout))
実行結果:
'a b c\n'
コマンドを文字列で書きたいときは、shlex.split()でリストに分けられます。
import shlex
print(shlex.split("git commit -m 'first commit'"))
実行結果:
['git', 'commit', '-m', 'first commit']
shell=Trueに外部の値を混ぜてはいけない
shell=Trueを付けると文字列がシェルに渡され、パイプ(|)やワイルドカード(*)が使えます。
r = subprocess.run("ls *.txt | wc -l", shell=True, capture_output=True, text=True)
print(r.stdout.strip())
実行結果:
1
ただし、ユーザー入力など外から来た値を文字列に埋め込むと、別のコマンドを実行されてしまいます。
user_input = "demo; echo '←ここで別のコマンドが動いた'"
r = subprocess.run(f"ls {user_input}", shell=True, capture_output=True, text=True)
print(r.stdout)
実行結果:
←ここで別のコマンドが動いた
;から後ろが別のコマンドとして実行されました。これがコマンドインジェクションと呼ばれる脆弱性です。リストで渡すか、どうしてもシェルが必要ならshlex.quote()で値をエスケープします。
r = subprocess.run(["ls", user_input], capture_output=True, text=True)
print(r.returncode, r.stderr.strip())
r = subprocess.run(f"ls {shlex.quote(user_input)}", shell=True,
capture_output=True, text=True)
print(r.returncode, r.stderr.strip())
実行結果:
1 ls: demo; echo '←ここで別のコマンドが動いた': No such file or directory
1 ls: demo; echo '←ここで別のコマンドが動いた': No such file or directory
どちらも、文字列全体が1つのファイル名として扱われ、コマンドとしては実行されていません。
Windowsでの注意
公式ドキュメントによると、Windowsでshell=Trueが必要なのはdirやcopyのようなシェルの組み込みコマンドを実行するときだけで、バッチファイルやコンソールアプリの実行には不要です。また、この記事の例で使っているecho・ls・wc・sleepはmacOS・Linuxのコマンドなので、Windowsでは動きません。OSに依存しない例にしたいときは、次のようにPython自身を呼び出すと確実です。
import sys
r = subprocess.run([sys.executable, "--version"], capture_output=True, text=True, check=True)
print(r.stdout.strip())
実行結果:
Python 3.12.15
sys.executableは実行中のPythonの絶対パスです(sysモジュールの関数一覧で解説)。
よく使う引数|cwd・env・input
| 引数 | 役割 |
|---|---|
capture_output=True |
標準出力・エラー出力を受け取る |
text=True |
bytesではなく文字列で扱う |
encoding="utf-8" |
文字コードを指定する(指定すると文字列モードになる) |
check=True |
終了コードが0以外なら例外を出す |
timeout=秒 |
時間切れで打ち切る |
cwd="パス" |
作業ディレクトリを変えて実行する |
env={...} |
環境変数を指定する |
input="文字列" |
標準入力に渡す |
shell=True |
シェル経由で実行する(外部の値を混ぜない) |
import os, sys, subprocess
# 作業ディレクトリを変える
r = subprocess.run(["pwd"], cwd="demo", capture_output=True, text=True)
print(r.stdout.strip().split("/")[-1])
# 環境変数を足す(os.environを引き継がないとPATHなどが消える)
env = os.environ.copy()
env["GREETING"] = "こんにちは"
r = subprocess.run([sys.executable, "-c", "import os; print(os.environ['GREETING'])"],
env=env, capture_output=True, text=True)
print(r.stdout.strip())
# 標準入力に渡す
r = subprocess.run(["wc", "-l"], input="a\nb\nc\n", capture_output=True, text=True)
print("行数:", r.stdout.strip())
実行結果:
demo
こんにちは
行数: 3
envに辞書を渡すと、子プロセスの環境変数はその辞書だけになります。足したいだけならos.environ.copy()に追加する形で、元の環境変数を引き継いでください。環境変数の扱いはos.environの使い方にまとめています。
run()とPopen・古い関数の使い分け
| やりたいこと | 使うもの |
|---|---|
| コマンドを実行して、終わったら結果を受け取る | run() |
| 実行中の出力を1行ずつ読みたい・終了を待たずに別の処理をしたい | Popen |
古いコードのcall(cmd) |
run(cmd).returncodeと同じ |
古いコードのcheck_call(cmd) |
run(cmd, check=True)と同じ |
古いコードのcheck_output(cmd) |
run(cmd, capture_output=True, check=True).stdoutとほぼ同じ |
新しく書くならrun()を覚えれば十分で、足りない場面だけsubprocess.Popen()を使います。なお公式ドキュメントでは、subprocessモジュールはAndroid・iOS・WASIでは使えないと明記されています。
よくある質問
Q. subprocess.run()の戻り値は何ですか?
CompletedProcessオブジェクトです。returncode(終了コード)、stdout(標準出力)、stderr(標準エラー出力)、args(実行したコマンド)を持っています。出力はcapture_output=Trueなどで受け取る設定にしたときだけ入り、そうでなければNoneです。
Q. 出力が b’…’ と表示されるのはなぜですか?
text=Trueを指定していないため、出力がバイト列(bytes)のまま返っているからです。text=Trueかencoding=”utf-8″を指定すると文字列になります。
Q. コマンドが失敗したのにエラーにならないのはなぜですか?
run()は終了コードが0以外でも例外を出さないのが既定の動きだからです。check=Trueを付けるとCalledProcessErrorが出るようになります。付けない場合はreturncodeを自分で確認してください。
Q. shell=Trueは使ってはいけないのですか?
パイプやワイルドカードなどシェルの機能が必要なら使えますが、ユーザー入力など外部の値を文字列に埋め込むとコマンドインジェクションの危険があります。可能ならリストで渡し、どうしても必要ならshlex.quote()で値をエスケープしてください。
まとめ
- 基本形は
subprocess.run([...], capture_output=True, text=True, check=True) - 戻り値は
CompletedProcess。returncode・stdout・stderrを見る text=Trueがないとbytes、check=Trueがないと失敗しても止まらない- コマンドはリストで渡し、
shell=Trueに外部の値を混ぜない - 自動処理には
timeout、環境変数はos.environ.copy()に足して渡す




