subprocess --- サブプロセス管理

ソースコード: Lib/subprocess.py


subprocess モジュールは新しいプロセスの開始、入力/出力/エラーパイプの接続、リターンコードの取得を可能とします。このモジュールは以下の古いモジュールや関数を置き換えることを目的としています:

os.system
os.spawn*

これらのモジュールや関数の代わりに、subprocess モジュールをどのように使うかについてを以下の節で説明します。

参考

PEP 324 -- subprocess モジュールを提案している PEP

利用可能性: Emscripten でなく、WASI でもないこと。

このモジュールは WebAssembly プラットフォーム wasm32-emscriptenwasm32-wasi では動作しないか、利用不可です。詳しくは、WebAssemblyプラットフォーム を見てください。

subprocess モジュールを使う

サブプロセスを起動するために推奨される方法は、すべての用法を扱える run() 関数を使用することです。より高度な用法では下層の Popen インターフェースを直接使用することもできます。

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)

args で指定されたコマンドを実行します。コマンドの完了を待って、CompletedProcess インスタンスを返します。

上記の引数は、もっともよく使われるものだけ示しており、後述の よく使われる引数 で説明されています (そのためここではキーワード専用引数の表記に省略されています)。関数の完全な使用法を説明しても大部分が Popen コンストラクターの内容と同じになります - この関数のほとんどの引数は Popen インターフェイスに渡されます。(timeoutinput および check は除く。)

capture_output を true に設定すると、stdout および stderr が捕捉されます。 このとき、内部では stdout=PIPE および stderr=PIPE に設定された Popen オブジェクトが自動的に作られます。なお、stdout または stderr 引数を capture_output と同時に指定することはできません。両者をまとめてひとつのストリームとして捕捉したい場合は、capture_output を指定するのではなく、stdout=PIPE and stderr=STDOUT を指定してください。

A timeout may be specified in seconds, it is internally passed on to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated. The initial process creation itself cannot be interrupted on many platform APIs so you are not guaranteed to see a timeout exception until at least after however long process creation takes.

引数 inputPopen.communicate() を経由し、サブプロセスの標準入力に渡されます。これはバイト列であるか、(encoding もしくは errors が指定されているか、text 引数が true である場合は) 文字列でなければなりません。この引数が指定されると、内部で Popen オブジェクトが stdin=PIPE で自動的に作成され、引数 stdin は使用されません。

check に真を指定した場合、プロセスが非ゼロの終了コードで終了すると CalledProcessError 例外が送出されます。 この例外の属性には、引数、終了コード、標準出力および標準エラー出力が捕捉できた場合に格納されます。

encoding または errors 引数が指定されるか、text 引数が true である場合、stdin, stdout および stderr のためのファイルオブジェクトはテキストモードでオープンされます。 その際には指定された encoding および errors が使われるか、デフォルトの io.TextIOWrapper になります。universal_newlines 引数は text 引数と等価であり、後方互換性のために提供されています。そうでない場合、デフォルトでこれらのファイルオブジェクトはバイナリモードでオープンされます。

envNone 以外の場合、これは新しいプロセスでの環境変数を定義します。デフォルトでは、子プロセスは現在のプロセスの環境変数を引き継ぎます。 Popen に直接渡されます。あらゆるプラットフォームで os.environ のように文字列から文字列へ、またPOSIX プラットフォームにおいては os.environb のようにバイトからバイトへも、定義すること出来ます。

例:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')

バージョン 3.5 で追加.

バージョン 3.6 で変更: encodingerror が引数に追加されました。

バージョン 3.7 で変更: universal_newlines 引数のよりわかりやすい名前として、text 引数が追加されました。capture_output 引数が追加されました。

バージョン 3.12 で変更: shell=True のときのWindowsシェル検索順序を変更しました。カレントディレクトリと %PATH% は、 %COMSPEC%%SystemRoot%\System32\cmd.exe に置き換えられました。これにより、 cmd.exe という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。

class subprocess.CompletedProcess

run() の戻り値。プロセスが終了したことを表します。

args

プロセスを起動するときに使用された引数。1 個のリストか 1 個の文字列になります。

returncode

子プロセスの終了コード。一般に、終了ステータス 0 はプロセスが正常に終了したことを示します。

負の値 -N は子プロセスがシグナル N により中止させられたことを示します (POSIX のみ)。

stdout

子プロセスから補足された標準出力です。バイト列、もしくは run() でエンコーディングが指定された場合、エラーの場合、text=True が指定された場合は文字列です。標準出力が補足できなかったら None になります。

プロセスが stderr=subprocess.STDOUT で実行された場合、標準出力と標準エラー出力が混合されたものがこの属性に格納され、stderrNone になります。

stderr

子プロセスから補足された標準エラー出力です。バイト列、もしくは run() でエンコーディングが指定された場合、エラーの場合、text=True が指定された場合は文字列です。標準エラー出力が補足できなかったら None になります。

check_returncode()

returncode が非ゼロの場合、CalledProcessError が送出されます。

バージョン 3.5 で追加.

subprocess.DEVNULL

Popenstdin, stdout, stderr 引数に渡して、標準入出力を os.devnull から入出力するように指定するための特殊値です。

バージョン 3.3 で追加.

subprocess.PIPE

Popenstdin, stdout, stderr 引数に渡して、標準ストリームに対するパイプを開くことを指定するための特殊値です。Popen.communicate() に非常に有用です。

subprocess.STDOUT

Popenstderr 引数に渡して、標準エラー出力が標準出力と同じハンドルに出力されるように指定するための特殊値です。

exception subprocess.SubprocessError

このモジュールの他のすべての例外のための基底クラスです。

バージョン 3.3 で追加.

exception subprocess.TimeoutExpired

SubprocessError のサブクラスです。子プロセスの終了を待機している間にタイムアウトが発生した場合に送出されます。

cmd

子プロセスの生成に使用されるコマンド本文。

timeout

タイムアウト秒数。

output

run() にまたは check_output() によって捕捉された場合は、子プロセスの出力となり、それ以外の場合は None となります。text=True の設定に関係なく、出力が捕捉された場合は常に bytes となります。出力がない場合は b'' の代わりに``None`` のままになることがあります。

stdout

output の別名。stderr と対になります。

stderr

run() によって捕捉された場合、子プロセスの標準エラー出力が表示され、それ以外の場合は None となります。text=True の設定に関係なく、標準エラー出力を捕捉した場合は常に bytes となります。標準エラー出力がない場合は、b'' の代わりに None のままになることがあります。

バージョン 3.3 で追加.

バージョン 3.5 で変更: 属性 stdout および stderr が追加されました。

exception subprocess.CalledProcessError

SubprocessError のサブクラスです。check_call() または check_output()check=True であるときの run() 、によって実行されたプロセスが非ゼロの終了ステータスを返した場合に送出されます。

returncode

子プロセスの終了ステータスです。もしプロセスがシグナルによって終了したなら、これは負のシグナル番号になります。

cmd

子プロセスの生成に使用されるコマンド本文。

output

run() または check_output() によって捕捉された子プロセスの出力。捕捉されなかったら None になります。

stdout

output の別名。stderr と対になります。

stderr

run() によって捕捉された子プロセスの標準エラー出力。捕捉されなかったら None になります。

バージョン 3.5 で変更: 属性 stdout および stderr が追加されました。

よく使われる引数

幅広い使用例をサポートするために、Popen コンストラクター (とその他の簡易関数) は、多くのオプション引数を受け付けます。一般的な用法については、これらの引数の多くはデフォルト値のままで問題ありません。通常必要とされる引数は以下の通りです:

args はすべての呼び出しに必要で、文字列あるいはプログラム引数のシーケンスでなければなりません。一般に、引数のシーケンスを渡す方が望ましいです。なぜなら、モジュールが必要な引数のエスケープやクオート (例えばファイル名中のスペースを許すこと) の面倒を見ることができるためです。単一の文字列を渡す場合、shellTrue でなければなりません (以下を参照)。もしくは、その文字列は引数を指定せずに実行される単なるプログラムの名前でなければなりません。

stdin, stdout and stderr specify the executed program's standard input, standard output and standard error file handles, respectively. Valid values are None, PIPE, DEVNULL, an existing file descriptor (a positive integer), and an existing file object with a valid file descriptor. With the default settings of None, no redirection will occur. PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. Additionally, stderr can be STDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.

If encoding or errors are specified, or text (also known as universal_newlines) is true, the file objects stdin, stdout and stderr will be opened in text mode using the encoding and errors specified in the call or the defaults for io.TextIOWrapper.

stdin については、入力での行末文字 '\n' はデフォルトの行セパレーター os.linesep に変換されます。stdoutstderr については、出力での行末はすべて '\n' に変換されます。詳細は io.TextIOWrapper クラスのドキュメントでコンストラクターの引数 newlineNone である場合を参照してください。

If text mode is not used, stdin, stdout and stderr will be opened as binary streams. No encoding or line ending conversion is performed.

バージョン 3.6 で変更: Added the encoding and errors parameters.

バージョン 3.7 で変更: universal_newlines の別名として、text 引数が追加されました。

注釈

ファイルオブジェクト Popen.stdinPopen.stdout ならびに Popen.stderr の改行属性は Popen.communicate() メソッドで更新されません。

shellTrue なら、指定されたコマンドはシェルによって実行されます。あなたが Python を主として (ほとんどのシステムシェル以上の) 強化された制御フローのために使用していて、さらにシェルパイプ、ファイル名ワイルドカード、環境変数展開、~ のユーザーホームディレクトリへの展開のような他のシェル機能への簡単なアクセスを望むなら、これは有用かもしれません。しかしながら、Python 自身が多くのシェル的な機能の実装を提供していることに注意してください (特に glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), shutil)。

バージョン 3.3 で変更: universal_newlinesTrue の場合、クラスはエンコーディング locale.getpreferredencoding() の代わりに locale.getpreferredencoding(False) を使用します。この変更についての詳細は、 io.TextIOWrapper クラスを参照してください。

注釈

shell=True を使う前に セキュリティで考慮すべき点 を読んでください。

これらのオプションは、他のすべてのオプションとともに Popen コンストラクターのドキュメントの中でより詳細に説明されています。

Popen コンストラクター

このモジュールの中で、根底のプロセス生成と管理は Popen クラスによって扱われます。簡易関数によってカバーされないあまり一般的でないケースを開発者が扱えるように、Popen クラスは多くの柔軟性を提供しています。

class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None, pipesize=-1, process_group=None)

新しいプロセスで子のプログラムを実行します。POSIX においては、子のプログラムを実行するために、このクラスは os.execvpe() のような挙動を使用します。Windows においては、このクラスは Windows の CreateProcess() 関数を使用します。Popen への引数は以下の通りです。

args はプログラム引数のシーケンスか、単一の文字列または path-like object でなければなりません。デフォルトでは、args がシーケンスの場合に実行されるプログラムは args の最初の要素です。args が文字列の場合、解釈はプラットフォーム依存であり、下記に説明されます。デフォルトの挙動からの追加の違いについては shell および executable 引数を参照してください。特に明記されない限り、args をシーケンスとして渡すことが推奨されます。

警告

For maximum reliability, use a fully qualified path for the executable. To search for an unqualified name on PATH, use shutil.which(). On all platforms, passing sys.executable is the recommended way to launch the current Python interpreter again, and use the -m command-line format to launch an installed module.

Resolving the path of executable (or the first item of args) is platform dependent. For POSIX, see os.execvpe(), and note that when resolving or searching for the executable path, cwd overrides the current working directory and env can override the PATH environment variable. For Windows, see the documentation of the lpApplicationName and lpCommandLine parameters of WinAPI CreateProcess, and note that when resolving or searching for the executable path with shell=False, cwd does not override the current working directory and env cannot override the PATH environment variable. Using a full path avoids all of these variations.

An example of passing some arguments to an external program as a sequence is:

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])

POSIX 上では、args が文字列の場合、その文字列は実行すべきプログラムの名前またはパスとして解釈されます。しかし、これはプログラムに引数を渡さない場合にのみ可能です。

注釈

It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can illustrate how to determine the correct tokenization for args:

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

特に注意すべき点は、シェル内でスペースで区切られたオプション (-input など) と引数 (eggs.txt など) はリストの別々の要素になるのに対し、シェル内で (上記のスペースを含むファイル名や echo コマンドのように) クォーティングやバックスラッシュエスケープが必要なものは単一のリスト要素であることです。

Windows 上では、args がシーケンスなら Windows における引数シーケンスから文字列への変換 に記述された方法で文字列に変換されます。これは根底の CreateProcess() が文字列上で動作するからです。

バージョン 3.6 で変更: args parameter accepts a path-like object if shell is False and a sequence containing path-like objects on POSIX.

バージョン 3.8 で変更: args parameter accepts a path-like object if shell is False and a sequence containing bytes and path-like objects on Windows.

shell 引数 (デフォルトでは False) は、実行するプログラムとしてシェルを使用するかどうかを指定します。 shellTrue の場合、 args をシーケンスとしてではなく文字列として渡すことが推奨されます。

POSIX で shell=True の場合、シェルのデフォルトは /bin/sh になります。args が文字列の場合、この文字列はシェルを介して実行されるコマンドを指定します。したがって、文字列は厳密にシェルプロンプトで打つ形式と一致しなければなりません。例えば、文字列の中にスペースを含むファイル名がある場合は、クォーティングやバックスラッシュエスケープが必要です。args がシーケンスの場合には、最初の要素はコマンド名を表わす文字列として、残りの要素は追加の引数としてシェルに渡されます。つまり、以下の Popen と等価ということです:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

Windows で shell=True とすると、COMSPEC 環境変数がデフォルトシェルを指定します。Windows で shell=True を指定する必要があるのは、実行したいコマンドがシェルに組み込みの場合だけです (例えば dircopy)。バッチファイルやコンソールベースの実行ファイルを実行するために shell=True は必要ありません。

注釈

shell=True を使う前に セキュリティで考慮すべき点 を読んでください。

bufsize は標準入力/標準出力/標準エラー出力パイプファイルオブジェクトを生成するときに open() 関数の対応する引数に渡されます:

  • 0 means unbuffered (read and write are one system call and can return short)

  • 1 means line buffered (only usable if text=True or universal_newlines=True)

  • それ以外の正の整数はバッファーのおよそのサイズになることを意味します。

  • 負のサイズ (デフォルト) は io.DEFAULT_BUFFER_SIZE のシステムデフォルトが使用されることを意味します。

バージョン 3.3.1 で変更: bufsize now defaults to -1 to enable buffering by default to match the behavior that most code expects. In versions prior to Python 3.2.4 and 3.3.1 it incorrectly defaulted to 0 which was unbuffered and allowed short reads. This was unintentional and did not match the behavior of Python 2 as most code expected.

executable 引数は、実行する置換プログラムを指定します。これが必要になるのは極めて稀です。shell=False のときは、executableargs で指定されている実行プログラムを置換します。しかし、オリジナルの args は依然としてプログラムに渡されます。ほとんどのプログラムは、args で指定されたプログラムをコマンド名として扱います。そして、それは実際に実行されたプログラムとは異なる可能性があります。POSIX において、ps のようなユーティリティの中では、args 名が実行ファイルの表示名になります。shell=True の場合、POSIX において executable 引数はデフォルトの /bin/sh に対する置換シェルを指定します。

バージョン 3.6 で変更: executable 引数が POSIX で path-like object を受け付けるようになりました。

バージョン 3.8 で変更: executable 引数が Windows で path-like object を受け付けるようになりました。

バージョン 3.12 で変更: shell=True のときのWindowsシェル検索順序を変更しました。カレントディレクトリと %PATH% は、 %COMSPEC%%SystemRoot%\System32\cmd.exe に置き換えられました。これにより、 cmd.exe という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。

stdin, stdout and stderr specify the executed program's standard input, standard output and standard error file handles, respectively. Valid values are None, PIPE, DEVNULL, an existing file descriptor (a positive integer), and an existing file object with a valid file descriptor. With the default settings of None, no redirection will occur. PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.

preexec_fn に呼び出し可能オブジェクトが指定されている場合、このオブジェクトは子プロセスが実行される直前 (fork されたあと、exec される直前) に子プロセス内で呼ばれます。(POSIXのみ)

警告

アプリケーション中に複数のスレッドが存在する状態で preexec_fn 引数を使用するのは**安全ではありません**。exec が呼ばれる前に子プロセスがデッドロックを起こすことがあります。

注釈

If you need to modify the environment for the child use the env parameter rather than doing it in a preexec_fn. The start_new_session and process_group parameters should take the place of code using preexec_fn to call os.setsid() or os.setpgid() in the child.

バージョン 3.8 で変更: The preexec_fn parameter is no longer supported in subinterpreters. The use of the parameter in a subinterpreter raises RuntimeError. The new restriction may affect applications that are deployed in mod_wsgi, uWSGI, and other embedded environments.

If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. Otherwise when close_fds is false, file descriptors obey their inheritable flag as described in ファイル記述子の継承.

On Windows, if close_fds is true then no handles will be inherited by the child process unless explicitly passed in the handle_list element of STARTUPINFO.lpAttributeList, or by standard handle redirection.

バージョン 3.2 で変更: close_fds のデフォルトは、False から上記のものに変更されました。

バージョン 3.7 で変更: On Windows the default for close_fds was changed from False to True when redirecting the standard handles. It's now possible to set close_fds to True when redirecting the standard handles.

pass_fds はオプションで、親と子の間で開いたままにしておくファイル記述子のシーケンスを指定します。何らかの pass_fds を渡した場合、close_fds は強制的に True になります。(POSIXのみ)

バージョン 3.2 で変更: pass_fds 引数が追加されました。

If cwd is not None, the function changes the working directory to cwd before executing the child. cwd can be a string, bytes or path-like object. On POSIX, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path.

バージョン 3.6 で変更: cwd 引数が POSIX で path-like object を受け付けるようになりました。

バージョン 3.7 で変更: cwd 引数が Windows で path-like object を受け付けるようになりました。

バージョン 3.8 で変更: cwd 引数が Windows で bytes オブジェクトを受け付けるようになりました。

restore_signals が真の場合 (デフォルト)、Python が SIG_IGN に設定したすべてのシグナルは子プロセスが exec される前に子プロセスの SIG_DFL に格納されます。現在これには SIGPIPE, SIGXFZ および SIGXFSZ シグナルが含まれています。(POSIX のみ)

バージョン 3.2 で変更: restore_signals が追加されました。

If start_new_session is true the setsid() system call will be made in the child process prior to the execution of the subprocess.

バージョン 3.2 で変更: start_new_session が追加されました。

If process_group is a non-negative integer, the setpgid(0, value) system call will be made in the child process prior to the execution of the subprocess.

バージョン 3.11 で変更: process_group was added.

If group is not None, the setregid() system call will be made in the child process prior to the execution of the subprocess. If the provided value is a string, it will be looked up via grp.getgrnam() and the value in gr_gid will be used. If the value is an integer, it will be passed verbatim. (POSIX only)

バージョン 3.9 で追加.

If extra_groups is not None, the setgroups() system call will be made in the child process prior to the execution of the subprocess. Strings provided in extra_groups will be looked up via grp.getgrnam() and the values in gr_gid will be used. Integer values will be passed verbatim. (POSIX only)

バージョン 3.9 で追加.

If user is not None, the setreuid() system call will be made in the child process prior to the execution of the subprocess. If the provided value is a string, it will be looked up via pwd.getpwnam() and the value in pw_uid will be used. If the value is an integer, it will be passed verbatim. (POSIX only)

バージョン 3.9 で追加.

If umask is not negative, the umask() system call will be made in the child process prior to the execution of the subprocess.

バージョン 3.9 で追加.

envNone 以外の場合、これは新しいプロセスでの環境変数を定義します。デフォルトでは、子プロセスは現在のプロセスの環境変数を引き継ぎます。あらゆるプラットフォームで os.environ のように文字列から文字列へ、またPOSIX プラットフォームにおいては os.environb のようにバイトからバイトへも、定義すること出来ます。

注釈

env を指定する場合、プログラムを実行するのに必要な変数すべてを与えなければなりません。Windows で Side-by-Side アセンブリ を実行するためには、env は正しい SystemRoot含まなければなりません

If encoding or errors are specified, or text is true, the file objects stdin, stdout and stderr are opened in text mode with the specified encoding and errors, as described above in よく使われる引数. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode.

バージョン 3.6 で追加: encodingerrors が追加されました。

バージョン 3.7 で追加: text が、universal_newlines のより読みやすい別名として追加されました。

If given, startupinfo will be a STARTUPINFO object, which is passed to the underlying CreateProcess function.

If given, creationflags, can be one or more of the following flags:

pipesize can be used to change the size of the pipe when PIPE is used for stdin, stdout or stderr. The size of the pipe is only changed on platforms that support this (only Linux at this time of writing). Other platforms will ignore this parameter.

バージョン 3.10 で変更: Added the pipesize parameter.

Popen オブジェクトは with 文によってコンテキストマネージャーとしてサポートされます: 終了時には標準ファイル記述子が閉じられ、プロセスを待機します:

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())

引数 executable, args, cwd, env を指定して 監査イベント subprocess.Popen を送出します。

バージョン 3.2 で変更: コンテキストマネージャーサポートが追加されました。

バージョン 3.6 で変更: Popen destructor now emits a ResourceWarning warning if the child process is still running.

バージョン 3.8 で変更: Popen can use os.posix_spawn() in some cases for better performance. On Windows Subsystem for Linux and QEMU User Emulation, Popen constructor using os.posix_spawn() no longer raise an exception on errors like missing program, but the child process fails with a non-zero returncode.

例外

Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent.

The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSError exceptions. Note that, when shell=True, OSError will be raised by the child only if the selected shell itself was not found. To determine if the shell failed to find the requested application, it is necessary to check the return code or output from the subprocess.

不正な引数で Popen が呼ばれた場合は ValueError が発生します。

呼び出されたプロセスが非ゼロのリターンコードを返した場合 check_call()check_output()CalledProcessError を送出します。

All of the functions and methods that accept a timeout parameter, such as run() and Popen.communicate() will raise TimeoutExpired if the timeout expires before the process exits.

このモジュールで定義されたすべての例外は SubprocessError を継承しています。

バージョン 3.3 で追加: SubprocessError 基底クラスが追加されました。

セキュリティで考慮すべき点

Unlike some other popen functions, this implementation will never implicitly call a system shell. This means that all characters, including shell metacharacters, can safely be passed to child processes. If the shell is invoked explicitly, via shell=True, it is the application's responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities. On some platforms, it is possible to use shlex.quote() for this escaping.

Popen オブジェクト

Popen クラスのインスタンスには、以下のようなメソッドがあります:

Popen.poll()

子プロセスが終了しているかどうかを調べます。 returncode 属性を設定して返します。そうでなければ None を返します。

Popen.wait(timeout=None)

子プロセスが終了するまで待ちます。returncode 属性を設定して返します。

プロセスが timeout 秒後に終了してない場合、TimeoutExpired 例外を送出します。この例外を捕捉して wait を再試行するのは安全です。

注釈

stdout=PIPEstderr=PIPE を使っていて、より多くのデータを受け入れるために OS のパイプバッファーをブロックしているパイプに子プロセスが十分な出力を生成した場合、デッドロックが発生します。これを避けるには Popen.communicate() を使用してください。

注釈

When the timeout parameter is not None, then (on POSIX) the function is implemented using a busy loop (non-blocking call and short sleeps). Use the asyncio module for an asynchronous wait: see asyncio.create_subprocess_exec.

バージョン 3.3 で変更: timeout が追加されました

Popen.communicate(input=None, timeout=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate and set the returncode attribute. The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child. If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.

communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.

子プロセスの標準入力にデータを送りたい場合は、 Popen オブジェクトを stdin=PIPE と指定して作成しなければなりません。同じく、戻り値のタプルから None ではない値を取得するためには、 stdout=PIPE かつ/または stderr=PIPE を指定しなければなりません。

プロセスが timeout 秒後に終了してない場合、TimeoutExpired 例外が送出されます。この例外を捕捉して通信を再試行しても出力データは失われません。

タイムアウトが発生した場合子プロセスは kill されません。したがって、適切にクリーンアップを行うために、正常に動作するアプリケーションは子プロセスを kill して通信を終了すべきです:

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

注釈

受信したデータはメモリにバッファーされます。そのため、返されるデータが大きいかあるいは制限がないような場合はこのメソッドを使うべきではありません。

バージョン 3.3 で変更: timeout が追加されました

Popen.send_signal(signal)

signal シグナルを子プロセスに送ります。

Do nothing if the process completed.

注釈

Windows では、SIGTERM は terminate() の別名です。CTRL_C_EVENT と CTRL_BREAK_EVENT を、CREATE_NEW_PROCESS_GROUP を含む creationflags で始まった、プロセスに送れます。

Popen.terminate()

Stop the child. On POSIX OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child.

Popen.kill()

子プロセスを kill します。POSIX OS では SIGKILL シグナルを子プロセスに送ります。Windows では、kill()terminate() の別名です。

The following attributes are also set by the class for you to access. Reassigning them to new values is unsupported:

Popen.args

Popen に渡された引数 args です -- プログラム引数のシーケンスまたは 1 個の文字列になります。

バージョン 3.3 で追加.

Popen.stdin

If the stdin argument was PIPE, this attribute is a writeable stream object as returned by open(). If the encoding or errors arguments were specified or the text or universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdin argument was not PIPE, this attribute is None.

Popen.stdout

If the stdout argument was PIPE, this attribute is a readable stream object as returned by open(). Reading from the stream provides output from the child process. If the encoding or errors arguments were specified or the text or universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdout argument was not PIPE, this attribute is None.

Popen.stderr

If the stderr argument was PIPE, this attribute is a readable stream object as returned by open(). Reading from the stream provides error output from the child process. If the encoding or errors arguments were specified or the text or universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stderr argument was not PIPE, this attribute is None.

警告

.stdin.write, .stdout.read, .stderr.read を利用すると、別のパイプの OS パイプバッファーがいっぱいになってデッドロックが発生する恐れがあります。これを避けるためには communicate() を利用してください。

Popen.pid

子プロセスのプロセス ID が入ります。

shell 引数を True に設定した場合は、生成されたシェルのプロセス ID になります。

Popen.returncode

The child return code. Initially None, returncode is set by a call to the poll(), wait(), or communicate() methods if they detect that the process has terminated.

A None value indicates that the process hadn't yet terminated at the time of the last method call.

負の値 -N は子プロセスがシグナル N により中止させられたことを示します (POSIX のみ)。

Windows Popen ヘルパー

STARTUPINFO クラスと以下の定数は、Windows のみで利用できます。

class subprocess.STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)

Partial support of the Windows STARTUPINFO structure is used for Popen creation. The following attributes can be set by passing them as keyword-only arguments.

バージョン 3.7 で変更: キーワード専用引数のサポートが追加されました。

dwFlags

特定の STARTUPINFO の属性が、プロセスがウィンドウを生成するときに使われるかを決定するビットフィールドです:

si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
hStdInput

dwFlagsSTARTF_USESTDHANDLES を指定すれば、この属性がプロセスの標準入力処理です。STARTF_USESTDHANDLES が指定されなければ、標準入力のデフォルトはキーボードバッファーです。

hStdOutput

dwFlagsSTARTF_USESTDHANDLES を指定すれば、この属性がプロセスの標準出力処理です。そうでなければ、この属性は無視され、標準出力のデフォルトはコンソールウィンドウのバッファーです。

hStdError

dwFlagsSTARTF_USESTDHANDLES を指定すれば、この属性がプロセスの標準エラー処理です。そうでなければ、この属性は無視され、標準エラー出力のデフォルトはコンソールウィンドウのバッファーです。

wShowWindow

dwFlagsSTARTF_USESHOWWINDOW を指定すれば、この属性は ShowWindow 関数の nCmdShow 引数で指定された値なら、 SW_SHOWDEFAULT 以外の任意のものにできます。しかし、この属性は無視されます。

この属性には SW_HIDE が提供されています。これは、Popenshell=True として呼び出されたときに使われます。

lpAttributeList

A dictionary of additional attributes for process creation as given in STARTUPINFOEX, see UpdateProcThreadAttribute.

Supported attributes:

handle_list

Sequence of handles that will be inherited. close_fds must be true if non-empty.

The handles must be temporarily made inheritable by os.set_handle_inheritable() when passed to the Popen constructor, else OSError will be raised with Windows error ERROR_INVALID_PARAMETER (87).

警告

In a multithreaded process, use caution to avoid leaking handles that are marked inheritable when combining this feature with concurrent calls to other process creation functions that inherit all handles such as os.system(). This also applies to standard handle redirection, which temporarily creates inheritable handles.

バージョン 3.7 で追加.

Windows Constants

subprocess モジュールは、以下の定数を公開しています。

subprocess.STD_INPUT_HANDLE

標準入力デバイスです。この初期値は、コンソール入力バッファ、 CONIN$ です。

subprocess.STD_OUTPUT_HANDLE

標準出力デバイスです。この初期値は、アクティブコンソールスクリーン、 CONOUT$ です。

subprocess.STD_ERROR_HANDLE

標準エラーデバイスです。この初期値は、アクティブコンソールスクリーン、 CONOUT$ です。

subprocess.SW_HIDE

ウィンドウを隠します。別のウィンドウがアクティブになります。

subprocess.STARTF_USESTDHANDLES

追加情報を保持する、STARTUPINFO.hStdInput, STARTUPINFO.hStdOutput, および STARTUPINFO.hStdError 属性を指定します。

subprocess.STARTF_USESHOWWINDOW

追加情報を保持する、 STARTUPINFO.wShowWindow 属性を指定します。

subprocess.CREATE_NEW_CONSOLE

新しいプロセスが、親プロセスのコンソールを継承する (デフォルト) のではなく、新しいコンソールを持ちます。

subprocess.CREATE_NEW_PROCESS_GROUP

新しいプロセスグループが生成されることを指定する Popen creationflags パラメーターです。このフラグは、サブプロセスで os.kill() を使うのに必要です。

CREATE_NEW_CONSOLE が指定されていたら、このフラグは無視されます。

subprocess.ABOVE_NORMAL_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have an above average priority.

バージョン 3.7 で追加.

subprocess.BELOW_NORMAL_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have a below average priority.

バージョン 3.7 で追加.

subprocess.HIGH_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have a high priority.

バージョン 3.7 で追加.

subprocess.IDLE_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have an idle (lowest) priority.

バージョン 3.7 で追加.

subprocess.NORMAL_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have an normal priority. (default)

バージョン 3.7 で追加.

subprocess.REALTIME_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have realtime priority. You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts system threads that manage mouse input, keyboard input, and background disk flushing. This class can be appropriate for applications that "talk" directly to hardware or that perform brief tasks that should have limited interruptions.

バージョン 3.7 で追加.

subprocess.CREATE_NO_WINDOW

A Popen creationflags parameter to specify that a new process will not create a window.

バージョン 3.7 で追加.

subprocess.DETACHED_PROCESS

A Popen creationflags parameter to specify that a new process will not inherit its parent's console. This value cannot be used with CREATE_NEW_CONSOLE.

バージョン 3.7 で追加.

subprocess.CREATE_DEFAULT_ERROR_MODE

A Popen creationflags parameter to specify that a new process does not inherit the error mode of the calling process. Instead, the new process gets the default error mode. This feature is particularly useful for multithreaded shell applications that run with hard errors disabled.

バージョン 3.7 で追加.

subprocess.CREATE_BREAKAWAY_FROM_JOB

A Popen creationflags parameter to specify that a new process is not associated with the job.

バージョン 3.7 で追加.

古い高水準 API

Python 3.5 より前のバージョンでは、サブプロセスに対して以下の 3 つの関数からなる高水準 API が用意されていました。現在多くの場合 run() の使用で済みますが、既存の多くのコードではこれらの関数が使用されています。

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

args で指定されたコマンドを実行します。コマンドの終了を待ち、returncode 属性を返します。

Code needing to capture stdout or stderr should use run() instead:

run(...).returncode

To suppress stdout or stderr, supply a value of DEVNULL.

上記の引数は、よく使われるものだけ示しています。関数の全使用法は Popen コンストラクターの内容と同じになります - この関数は、このインターフェースに直接指定される timeout 以外は与えられた全引数を渡します。

注釈

この関数を使用する際は stdout=PIPE および stderr=PIPE を使用しないでください。子プロセスが OS のパイプバッファーを埋めてしまうほどの出力データを生成した場合、パイプからは読み込まれないので、子プロセスがブロックされることがあります。

バージョン 3.3 で変更: timeout が追加されました

バージョン 3.12 で変更: shell=True のときのWindowsシェル検索順序を変更しました。カレントディレクトリと %PATH% は、 %COMSPEC%%SystemRoot%\System32\cmd.exe に置き換えられました。これにより、 cmd.exe という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. If check_call() was unable to start the process it will propagate the exception that was raised.

Code needing to capture stdout or stderr should use run() instead:

run(..., check=True)

To suppress stdout or stderr, supply a value of DEVNULL.

上記の引数は、よく使われるものだけ示しています。関数の全使用法は Popen コンストラクターの内容と同じになります - この関数は、このインターフェースに直接指定される timeout 以外は与えられた全引数を渡します。

注釈

この関数を使用する際は stdout=PIPE および stderr=PIPE を使用しないでください。子プロセスが OS のパイプバッファーを埋めてしまうほどの出力データを生成した場合、パイプからは読み込まれないので、子プロセスがブロックされることがあります。

バージョン 3.3 で変更: timeout が追加されました

バージョン 3.12 で変更: shell=True のときのWindowsシェル検索順序を変更しました。カレントディレクトリと %PATH% は、 %COMSPEC%%SystemRoot%\System32\cmd.exe に置き換えられました。これにより、 cmd.exe という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)

引数でコマンドを実行し、その出力を返します。

コマンドのリターンコードが非ゼロならば CalledProcessError 例外が送出されます。CalledProcessError オブジェクトには、リターンコードが returncode 属性に、コマンドからの出力が output 属性に、それぞれ格納されています。

これは次と等価です:

run(..., check=True, stdout=PIPE).stdout

The arguments shown above are merely some common ones. The full function signature is largely the same as that of run() - most arguments are passed directly through to that interface. One API deviation from run() behavior exists: passing input=None will behave the same as input=b'' (or input='', depending on other arguments) rather than using the parent's standard input file handle.

デフォルトで、この関数はデータをエンコードされたバイトとして返します。出力されたデータの実際のエンコードは起動されているコマンドに依存するため、テキストへのデコードは通常アプリケーションレベルで扱う必要があります。

This behaviour may be overridden by setting text, encoding, errors, or universal_newlines to True as described in よく使われる引数 and run().

標準エラー出力も結果に含めるには、stderr=subprocess.STDOUT を使います:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

バージョン 3.1 で追加.

バージョン 3.3 で変更: timeout が追加されました

バージョン 3.4 で変更: キーワード引数 input が追加されました。

バージョン 3.6 で変更: encoding and errors were added. See run() for details.

バージョン 3.7 で追加: text が、universal_newlines のより読みやすい別名として追加されました。

バージョン 3.12 で変更: shell=True のときのWindowsシェル検索順序を変更しました。カレントディレクトリと %PATH% は、 %COMSPEC%%SystemRoot%\System32\cmd.exe に置き換えられました。これにより、 cmd.exe という名前の悪意のあるプログラムをカレントディレクトリにドロップしても、動作しなくなりました。

古い関数を subprocess モジュールで置き換える

この節では、 "a becomes b" と書かれているものは a の代替として b が使えるということを表します。

注釈

この節で紹介されている "a" 関数は全て、実行するプログラムが見つからないときは (おおむね) 静かに終了します。それに対して "b" 代替手段は OSError 例外を送出します。

また、要求された操作が非ゼロの終了コードを返した場合、check_output() を使用した置き換えは CalledProcessError で失敗します。その出力は、送出された例外の output 属性として利用可能です。

以下の例では、適切な関数が subprocess モジュールからすでにインポートされていることを前提としています。

Replacing /bin/sh shell command substitution

output=$(mycmd myarg)

これは以下のようになります:

output = check_output(["mycmd", "myarg"])

シェルのパイプラインを置き換える

output=$(dmesg | grep hda)

これは以下のようになります:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

p2 を開始した後の p1.stdout.close() の呼び出しは、p1 が p2 の前に存在した場合に、p1 が SIGPIPE を受け取るために重要です。

あるいは、信頼された入力に対しては、シェル自身のパイプラインサポートを直接使用することもできます:

output=$(dmesg | grep hda)

これは以下のようになります:

output = check_output("dmesg | grep hda", shell=True)

os.system() を置き換える

sts = os.system("mycmd" + " myarg")
# becomes
retcode = call("mycmd" + " myarg", shell=True)

注釈:

  • このプログラムは普通シェル経由で呼び出す必要はありません。

  • The call() return value is encoded differently to that of os.system().

  • The os.system() function ignores SIGINT and SIGQUIT signals while the command is running, but the caller must do this separately when using the subprocess module.

より現実的な例ではこうなるでしょう:

try:
    retcode = call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print("Child was terminated by signal", -retcode, file=sys.stderr)
    else:
        print("Child returned", retcode, file=sys.stderr)
except OSError as e:
    print("Execution failed:", e, file=sys.stderr)

os.spawn 関数群を置き換える

P_NOWAIT の例:

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid

P_WAIT の例:

retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])

シーケンスを使った例:

os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])

環境変数を使った例:

os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})

os.popen(), os.popen2(), os.popen3() を置き換える

(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
(child_stdin,
 child_stdout,
 child_stderr) = os.popen3(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
 child_stdout,
 child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

終了コードハンドリングは以下のように解釈します:

pipe = os.popen(cmd, 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
    print("There were some errors")
==>
process = Popen(cmd, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
    print("There were some errors")

Replacing functions from the popen2 module

注釈

popen2 関数の cmd 引数が文字列の場合、コマンドは /bin/sh によって実行されます。リストの場合、コマンドは直接実行されます。

(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen("somestring", shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)

popen2.Popen3 および popen2.Popen4 は以下の点を除けば、基本的に subprocess.Popen と同じです:

  • Popen は実行が失敗した場合に例外を送出します。

  • capturestderr 引数は stderr 引数に代わりました。

  • stdin=PIPE および stdout=PIPE を指定する必要があります。

  • popen2 はデフォルトですべてのファイル記述子を閉じます。しかし、全てのプラットフォーム上で、あるいは過去の Python バージョンでこの挙動を保証するためには、 Popen に対して close_fds=True を指定しなければなりません。

レガシーなシェル呼び出し関数

このモジュールでは、以下のような 2.x commands モジュールからのレガシー関数も提供しています。これらの操作は、暗黙的にシステムシェルを起動します。また、セキュリティに関して上述した保証や例外処理一貫性は、これらの関数では有効ではありません。

subprocess.getstatusoutput(cmd, *, encoding=None, errors=None)

シェル中の cmd を実行して (exitcode, output) を返します。

Execute the string cmd in a shell with Popen.check_output() and return a 2-tuple (exitcode, output). encoding and errors are used to decode output; see the notes on よく使われる引数 for more details.

A trailing newline is stripped from the output. The exit code for the command can be interpreted as the return code of subprocess. Example:

>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> subprocess.getstatusoutput('cat /bin/junk')
(1, 'cat: /bin/junk: No such file or directory')
>>> subprocess.getstatusoutput('/bin/junk')
(127, 'sh: /bin/junk: not found')
>>> subprocess.getstatusoutput('/bin/kill $$')
(-15, '')

Availability: Unix, Windows。

バージョン 3.3.4 で変更: Windows のサポートが追加されました。

The function now returns (exitcode, output) instead of (status, output) as it did in Python 3.3.3 and earlier. exitcode has the same value as returncode.

バージョン 3.11 で変更: Added the encoding and errors parameters.

subprocess.getoutput(cmd, *, encoding=None, errors=None)

シェル中の cmd を実行して出力 (stdout と stderr) を返します。

getstatusoutput() に似ていますが、終了コードは無視され、コマンドの出力のみを返します。例えば:

>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'

Availability: Unix, Windows。

バージョン 3.3.4 で変更: Windowsで利用可能になりました

バージョン 3.11 で変更: Added the encoding and errors parameters.

注釈

Windows における引数シーケンスから文字列への変換

Windows では、 args シーケンスは以下の (MS C ランタイムで使われる規則に対応する) 規則を使って解析できる文字列に変換されます:

  1. 引数は、スペースかタブのどちらかの空白で分けられます。

  2. ダブルクオーテーションマークで囲まれた文字列は、空白が含まれていたとしても 1 つの引数として解釈されます。クオートされた文字列は引数に埋め込めます。

  3. バックスラッシュに続くダブルクオーテーションマークは、リテラルのダブルクオーテーションマークと解釈されます。

  4. バックスラッシュは、ダブルクオーテーションが続かない限り、リテラルとして解釈されます。

  5. 複数のバックスラッシュにダブルクオーテーションマークが続くなら、バックスラッシュ 2 つで 1 つのバックスラッシュ文字と解釈されます。バックスラッシュの数が奇数なら、最後のバックスラッシュは規則 3 に従って続くダブルクオーテーションマークをエスケープします。

参考

shlex

コマンドラインを解析したりエスケープしたりする関数を提供するモジュール。

Disabling use of vfork() or posix_spawn()

On Linux, subprocess defaults to using the vfork() system call internally when it is safe to do so rather than fork(). This greatly improves performance.

If you ever encounter a presumed highly unusual situation where you need to prevent vfork() from being used by Python, you can set the subprocess._USE_VFORK attribute to a false value.

subprocess._USE_VFORK = False  # See CPython issue gh-NNNNNN.

Setting this has no impact on use of posix_spawn() which could use vfork() internally within its libc implementation. There is a similar subprocess._USE_POSIX_SPAWN attribute if you need to prevent use of that.

subprocess._USE_POSIX_SPAWN = False  # See CPython issue gh-NNNNNN.

It is safe to set these to false on any Python version. They will have no effect on older versions when unsupported. Do not assume the attributes are available to read. Despite their names, a true value does not indicate that the corresponding function will be used, only that it may be.

Please file issues any time you have to use these private knobs with a way to reproduce the issue you were seeing. Link to that issue from a comment in your code.

バージョン 3.8 で追加: _USE_POSIX_SPAWN

バージョン 3.11 で追加: _USE_VFORK