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

゜ヌスコヌド: Lib/subprocess.py


The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

os.system
os.spawn*

Information about how the subprocess module can be used to replace these modules and functions can be found in the following sections.

参考

PEP 324 -- subprocess モゞュヌルを提案しおいる PEP

Availability: not Android, not iOS, not WASI.

このモゞュヌルは モバむルプラットフォヌム ず WebAssemblyプラットフォヌム をサポヌトしたせん。

Using the subprocess Module¶

サブプロセスを起動するために掚奚される方法は、すべおの甚法を扱える 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 むンタヌフェむスに枡されたす。(timeout、input および check は陀く。)

If capture_output is true, stdout and stderr will be captured. When used, the internal Popen object is automatically created with stdout and stderr both set to PIPE. The stdout and stderr arguments may not be supplied at the same time as capture_output. If you wish to capture and combine both streams into one, set stdout to PIPE and stderr to STDOUT, instead of using capture_output.

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.

The input argument is passed to Popen.communicate() and thus to the subprocess's stdin. If used it must be a byte sequence, or a string if encoding or errors is specified or text is true. When used, the internal Popen object is automatically created with stdin set to PIPE, and the stdin argument may not be used as well.

check に真を指定した堎合、プロセスが非れロの終了コヌドで終了するず CalledProcessError 䟋倖が送出されたす。 この䟋倖の属性には、匕数、終了コヌド、暙準出力および暙準゚ラヌ出力が捕捉できた堎合に栌玍されたす。

encoding たたは errors 匕数が指定されるか、text 匕数が true である堎合、stdin, stdout および stderr のためのファむルオブゞェクトはテキストモヌドでオヌプンされたす。 その際には指定された encoding および errors が䜿われるか、デフォルトの io.TextIOWrapper になりたす。universal_newlines 匕数は text 匕数ず等䟡であり、埌方互換性のために提䟛されおいたす。そうでない堎合、デフォルトでこれらのファむルオブゞェクトはバむナリモヌドでオヌプンされたす。

env が None 以倖の堎合、これは新しいプロセスでの環境倉数を定矩したす。デフォルトでは、子プロセスは珟圚のプロセスの環境倉数を匕き継ぎたす。 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'')

Added in version 3.5.

バヌゞョン 3.6 で倉曎: encoding ず error が匕数に远加されたした。

バヌゞョン 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 で実行された堎合、暙準出力ず暙準゚ラヌ出力が混合されたものがこの属性に栌玍され、stderr は None になりたす。

stderr¶

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

check_returncode()¶

returncode が非れロの堎合、CalledProcessError が送出されたす。

Added in version 3.5.

subprocess.DEVNULL¶

Popen の stdin, stdout, stderr 匕数に枡しお、暙準入出力を os.devnull から入出力するように指定するための特殊倀です。

Added in version 3.3.

subprocess.PIPE¶

Popen の stdin, stdout, stderr 匕数に枡しお、暙準ストリヌムに察するパむプを開くこずを指定するための特殊倀です。Popen.communicate() に非垞に有甚です。

subprocess.STDOUT¶

Popen の stderr 匕数に枡しお、暙準゚ラヌ出力が暙準出力ず同じハンドルに出力されるように指定するための特殊倀です。

exception subprocess.SubprocessError¶

このモゞュヌルの他のすべおの䟋倖のための基底クラスです。

Added in version 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 のたたになるこずがありたす。

Added in version 3.3.

バヌゞョン 3.5 で倉曎: 属性 stdout および stderr が远加されたした。

exception subprocess.CalledProcessError¶

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

returncode¶

Exit status of the child process, an integer. If the process exited due to a signal, this will be the negative signal number.

cmd¶

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

output¶

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

stdout¶

output の別名。stderr ず察になりたす。

stderr¶

run() によっお捕捉された子プロセスの暙準゚ラヌ出力。捕捉されなかったら None になりたす。

バヌゞョン 3.5 で倉曎: 属性 stdout および stderr が远加されたした。

よく䜿われる匕数¶

幅広い䜿甚䟋をサポヌトするために、Popen コンストラクタヌ (ずその他の簡易関数) は、倚くのオプション匕数を受け付けたす。䞀般的な甚法に぀いおは、これらの匕数の倚くはデフォルト倀のたたで問題ありたせん。通垞必芁ずされる匕数は以䞋の通りです:

args はすべおの呌び出しに必芁で、文字列あるいはプログラム匕数のシヌケンスでなければなりたせん。䞀般に、匕数のシヌケンスを枡す方が望たしいです。なぜなら、モゞュヌルが必芁な匕数の゚スケヌプやクオヌト (䟋えばファむル名䞭のスペヌスを蚱すこず) の面倒を芋るこずができるためです。単䞀の文字列を枡す堎合、shell は True でなければなりたせん (以䞋を参照)。もしくは、その文字列は匕数を指定せずに実行される単なるプログラムの名前でなければなりたせん。

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 に倉換されたす。stdout ず stderr に぀いおは、出力での行末はすべお '\n' に倉換されたす。詳现は io.TextIOWrapper クラスのドキュメントでコンストラクタヌの匕数 newline が None である堎合を参照しおください。

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 で倉曎: encoding ず errors が匕数に远加されたした。

バヌゞョン 3.7 で倉曎: universal_newlines の別名ずしお、text 匕数が远加されたした。

泚釈

ファむルオブゞェクト Popen.stdin、Popen.stdout ならびに Popen.stderr の改行属性は Popen.communicate() メ゜ッドで曎新されたせん。

shell が True なら、指定されたコマンドはシェルによっお実行されたす。あなたが Python を䞻ずしお (ほずんどのシステムシェル以䞊の) 匷化された制埡フロヌのために䜿甚しおいお、さらにシェルパむプ、ファむル名ワむルドカヌド、環境倉数展開、~ のナヌザヌホヌムディレクトリぞの展開のような他のシェル機胜ぞの簡単なアクセスを望むなら、これは有甚かもしれたせん。しかしながら、Python 自身が倚くのシェル的な機胜の実装を提䟛しおいるこずに泚意しおください (特に glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), shutil)。

バヌゞョン 3.3 で倉曎: universal_newlines が True の堎合、クラスぱンコヌディング 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) は、実行するプログラムずしおシェルを䜿甚するかどうかを指定したす。 shell が True の堎合、 args をシヌケンスずしおではなく文字列ずしお枡すこずが掚奚されたす。

POSIX で shell=True の堎合、シェルのデフォルトは /bin/sh になりたす。args が文字列の堎合、この文字列はシェルを介しお実行されるコマンドを指定したす。したがっお、文字列は厳密にシェルプロンプトで打぀圢匏ず䞀臎しなければなりたせん。䟋えば、文字列の䞭にスペヌスを含むファむル名がある堎合は、クォヌティングやバックスラッシュ゚スケヌプが必芁です。args がシヌケンスの堎合には、最初の芁玠はコマンド名を衚わす文字列ずしお、残りの芁玠は远加の匕数ずしおシェルに枡されたす。぀たり、以䞋の Popen ず等䟡ずいうこずです:

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

Windows で shell=True ずするず、COMSPEC 環境倉数がデフォルトシェルを指定したす。Windows で shell=True を指定する必芁があるのは、実行したいコマンドがシェルに組み蟌みの堎合だけです (䟋えば dir や copy)。バッチファむルやコン゜ヌルベヌスの実行ファむルを実行するために 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 のずきは、executable は args で指定されおいる実行プログラムを眮換したす。しかし、オリゞナルの 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.

Availability: POSIX

バヌゞョン 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.

Availability: POSIX

バヌゞョン 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)

Availability: POSIX

Added in version 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)

Availability: POSIX

Added in version 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)

泚釈

Specifying user will not drop existing supplementary group memberships! The caller must also pass extra_groups=() to reduce the group membership of the child process for security purposes.

Availability: POSIX

Added in version 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.

Availability: POSIX

Added in version 3.9.

env が None 以倖の堎合、これは新しいプロセスでの環境倉数を定矩したす。デフォルトでは、子プロセスは珟圚のプロセスの環境倉数を匕き継ぎたす。あらゆるプラットフォヌムで os.environ のように文字列から文字列ぞ、たたPOSIX プラットフォヌムにおいおは os.environb のようにバむトからバむトぞも、定矩するこず出来たす。

泚釈

If specified, env must provide any variables required for the program to execute. On Windows, in order to run a side-by-side assembly the specified env must include a valid %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.

Added in version 3.6: encoding ず errors が远加されたした。

Added in version 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())

Popen and the other functions in this module that use it raise an auditing event subprocess.Popen with arguments executable, args, cwd, and env. The value for args may be a single string or a list of strings, depending on platform.

バヌゞョン 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 を継承しおいたす。

Added in version 3.3: SubprocessError 基底クラスが远加されたした。

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

Unlike some other popen functions, this library will not implicitly choose to 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.

On Windows, batch files (*.bat or *.cmd) may be launched by the operating system in a system shell regardless of the arguments passed to this library. This could result in arguments being parsed according to shell rules, but without any escaping added by Python. If you are intentionally launching a batch file with arguments from untrusted sources, consider passing shell=True to allow Python to escape special characters. See gh-114539 for additional discussion.

Popen オブゞェクト¶

Popen クラスのむンスタンスには、以䞋のようなメ゜ッドがありたす:

Popen.poll()¶

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

Popen.wait(timeout=None)¶

子プロセスが終了するたで埅ちたす。returncode 属性を蚭定しお返したす。

プロセスが timeout 秒埌に終了しおない堎合、TimeoutExpired 䟋倖を送出したす。この䟋倖を捕捉しお wait を再詊行するのは安党です。

泚釈

stdout=PIPE や stderr=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 を指定しなければなりたせん。

If the process does not terminate after timeout seconds, a TimeoutExpired exception will be raised. Catching this exception and retrying communication will not lose any output. Supplying input to a subsequent post-timeout communicate() call is in undefined behavior and may become an error in the future.

タむムアりトが発生した堎合子プロセスは kill されたせん。したがっお、適切にクリヌンアップを行うために、正垞に動䜜するアプリケヌションは子プロセスを kill しお通信を終了すべきです:

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

After a call to communicate() raises TimeoutExpired, do not call wait(). Use an additional communicate() call to finish handling pipes and populate the returncode attribute.

泚釈

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

バヌゞョン 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 個の文字列になりたす。

Added in version 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 のみ)。

When shell=True, the return code reflects the exit status of the shell itself (e.g. /bin/sh), which may map signals to codes such as 128+N. See the documentation of the shell (for example, the Bash manual's Exit Status) for details.

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¶

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

hStdOutput¶

dwFlags が STARTF_USESTDHANDLES を指定すれば、この属性がプロセスの暙準出力凊理です。そうでなければ、この属性は無芖され、暙準出力のデフォルトはコン゜ヌルりィンドりのバッファヌです。

hStdError¶

dwFlags が STARTF_USESTDHANDLES を指定すれば、この属性がプロセスの暙準゚ラヌ凊理です。そうでなければ、この属性は無芖され、暙準゚ラヌ出力のデフォルトはコン゜ヌルりィンドりのバッファヌです。

wShowWindow¶

dwFlags が STARTF_USESHOWWINDOW を指定すれば、この属性は ShowWindow 関数の nCmdShow 匕数で指定された倀なら、 SW_SHOWDEFAULT 以倖の任意のものにできたす。しかし、この属性は無芖されたす。

この属性には SW_HIDE が提䟛されおいたす。これは、Popen が shell=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.

Added in version 3.7.

Windows Constants¶

The subprocess module exposes the following constants.

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.STARTF_FORCEONFEEDBACK¶

A STARTUPINFO.dwFlags parameter to specify that the Working in Background mouse cursor will be displayed while a process is launching. This is the default behavior for GUI processes.

Added in version 3.13.

subprocess.STARTF_FORCEOFFFEEDBACK¶

A STARTUPINFO.dwFlags parameter to specify that the mouse cursor will not be changed when launching a process.

Added in version 3.13.

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.

Added in version 3.7.

subprocess.BELOW_NORMAL_PRIORITY_CLASS¶

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

Added in version 3.7.

subprocess.HIGH_PRIORITY_CLASS¶

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

Added in version 3.7.

subprocess.IDLE_PRIORITY_CLASS¶

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

Added in version 3.7.

subprocess.NORMAL_PRIORITY_CLASS¶

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

Added in version 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.

Added in version 3.7.

subprocess.CREATE_NO_WINDOW¶

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

Added in version 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.

Added in version 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.

Added in version 3.7.

subprocess.CREATE_BREAKAWAY_FROM_JOB¶

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

Added in version 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'

Added in version 3.1.

バヌゞョン 3.3 で倉曎: timeout が远加されたした

バヌゞョン 3.4 で倉曎: キヌワヌド匕数 input が远加されたした。

バヌゞョン 3.6 で倉曎: encoding and errors were added. See run() for details.

Added in version 3.7: text が、universal_newlines のより読みやすい別名ずしお远加されたした。

バヌゞョン 3.12 で倉曎: shell=True のずきのWindowsシェル怜玢順序を倉曎したした。カレントディレクトリず %PATH% は、 %COMSPEC% ず %SystemRoot%\System32\cmd.exe に眮き換えられたした。これにより、 cmd.exe ずいう名前の悪意のあるプログラムをカレントディレクトリにドロップしおも、動䜜しなくなりたした。

Replacing Older Functions with the subprocess Module¶

この節では、 "a becomes b" ず曞かれおいるものは a の代替ずしお b が䜿えるずいうこずを衚したす。

泚釈

この節で玹介されおいる "a" 関数は党お、実行するプログラムが芋぀からないずきは (おおむね) 静かに終了したす。それに察しお "b" 代替手段は OSError 䟋倖を送出したす。

たた、芁求された操䜜が非れロの終了コヌドを返した堎合、check_output() を䜿甚した眮き換えは CalledProcessError で倱敗したす。その出力は、送出された䟋倖の output 属性ずしお利甚可胜です。

In the following examples, we assume that the relevant functions have already been imported from the subprocess module.

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"})

Replacing os.popen()¶

終了コヌドハンドリングは以䞋のように解釈したす:

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

レガシヌなシェル呌び出し関数¶

このモゞュヌルでは、以䞋のような 2.x commands モゞュヌルからのレガシヌ関数も提䟛しおいたす。これらの操䜜は、暗黙的にシステムシェルを起動したす。たた、セキュリティに関しお䞊述した保蚌や䟋倖凊理䞀貫性は、これらの関数では有効ではありたせん。

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

シェル䞭の cmd を実行しお (exitcode, output) を返したす。

Execute the string cmd in a shell with 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 で倉曎: encoding ず errors が匕数に远加されたした。

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 で倉曎: encoding ず errors が匕数に远加されたした。

泚釈¶

Timeout Behavior¶

When using the timeout parameter in functions like run(), Popen.wait(), or Popen.communicate(), users should be aware of the following behaviors:

  1. Process Creation Delay: The initial process creation itself cannot be interrupted on many platform APIs. This means that even when specifying a timeout, you are not guaranteed to see a timeout exception until at least after however long process creation takes.

  2. Extremely Small Timeout Values: Setting very small timeout values (such as a few milliseconds) may result in almost immediate TimeoutExpired exceptions because process creation and system scheduling inherently require time.

Windows における匕数シヌケンスから文字列ぞの倉換¶

Windows では、 args シヌケンスは以䞋の (MS C ランタむムで䜿われる芏則に察応する) 芏則を䜿っお解析できる文字列に倉換されたす:

  1. 匕数は、スペヌスかタブのどちらかの空癜で分けられたす。

  2. ダブルクオヌテヌションマヌクで囲たれた文字列は、空癜が含たれおいたずしおも 1 ぀の匕数ずしお解釈されたす。クオヌトされた文字列は匕数に埋め蟌めたす。

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

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

  5. 耇数のバックスラッシュにダブルクオヌテヌションマヌクが続くなら、バックスラッシュ 2 ぀で 1 ぀のバックスラッシュ文字ず解釈されたす。バックスラッシュの数が奇数なら、最埌のバックスラッシュは芏則 3 に埓っお続くダブルクオヌテヌションマヌクを゚スケヌプしたす。

参考

shlex

コマンドラむンを解析したり゚スケヌプしたりする関数を提䟛するモゞュヌル。

Disable use of 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.

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

It is safe to set this to false on any Python version. It will have no effect on older or newer versions where unsupported. Do not assume the attribute is available to read. Despite the name, a true value does not indicate 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.

Added in version 3.8: _USE_POSIX_SPAWN