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

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

======================================================================

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

   os.system
   os.spawn*

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

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


"subprocess" モジュールを使う
=============================

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

"run()" 関数は Python 3.5 で追加されました; 過去のバージョンとの互換性
の維持が必要な場合は、古い高水準 API 節をご覧ください。

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* は除く。)

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

   引数 *timeout* は "Popen.communicate()" に渡されます。タイムアウト
   が発生すると、子プロセスは kill され、待機されます。子プロセスが中
   断されたあと "TimeoutExpired" が再び送出されます。

   引数 *input* は "Popen.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*
   引数と等価であり、後方互換性のために提供されています。そうでない場
   合、デフォルトでこれらのファイルオブジェクトはバイナリモードでオー
   プンされます。

   *env* が "None" 以外の場合、これは新しいプロセスでの環境変数を定義
   します。デフォルトでは、子プロセスは現在のプロセスの環境変数を引き
   継ぎます。 "Popen" に直接渡されます。

   例:

      >>> 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 で変更: *encoding* と *error* が引数に追加されました
   。

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

   バージョン 3.9.17 で変更: Changed Windows shell search order for
   "shell=True". The current directory and "%PATH%" are replaced with
   "%COMSPEC%" and "%SystemRoot%\System32\cmd.exe". As a result,
   dropping a malicious program named "cmd.exe" into a current
   directory no longer works.

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" が送出されます
      。

   バージョン 3.5 で追加.

subprocess.DEVNULL

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

   バージョン 3.3 で追加.

subprocess.PIPE

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

subprocess.STDOUT

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

exception subprocess.SubprocessError

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

   バージョン 3.3 で追加.

exception subprocess.TimeoutExpired

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

   cmd

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

   timeout

      タイムアウト秒数。

   output

      Output of the child process if it was captured by "run()" or
      "check_output()".  Otherwise, "None".  This is always "bytes"
      when any output was captured regardless of the "text=True"
      setting.  It may remain "None" instead of "b''" when no output
      was observed.

   stdout

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

   stderr

      Stderr output of the child process if it was captured by
      "run()". Otherwise, "None".  This is always "bytes" when stderr
      output was captured regardless of the "text=True" setting.  It
      may remain "None" instead of "b''" when no stderr output was
      observed.

   バージョン 3.3 で追加.

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

exception subprocess.CalledProcessError

   Subclass of "SubprocessError", raised when a process run by
   "check_call()", "check_output()", or "run()" (with "check=True")
   returns a non-zero exit status.

   returncode

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

   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 "PIPE", "DEVNULL", an existing file
   descriptor (a positive integer), an existing file object with a
   valid file descriptor, and "None". "PIPE" indicates that a new pipe
   to the child should be created. "DEVNULL" indicates that the
   special file "os.devnull" will be used.  With the default settings
   of "None", no redirection will occur; the child's file handles will
   be inherited from the parent. 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* と *error* がパラメータに追加され
   ました。

   バージョン 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)

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

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

   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" はバッファーされないことを意味します (読み込みおよび書き出し
     のたびにシステムコールが行われ、すぐに復帰します)。

   * "1" はラインバッファーを意味します ("universal_newlines=True"、す
     なわちテキストモードの場合のみ使用可能)。

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

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

   バージョン 3.3.1 で変更: ほとんどのコードが期待する振る舞いに合わせ
   てデフォルトでバッファリングが有効となるよう *bufsize* のデフォルト
   値が -1 になりました。Python 3.2.4 および 3.3.1 より前のバージョン
   では、誤ってバッファーされず短い読み込みを許可する "0" がデフォルト
   になっていました。これは意図したものではなく、ほとんどのコードが期
   待する Python 2 での振る舞いとも一致していませんでした。

   *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.9.17 で変更: Changed Windows shell search order for
   "shell=True". The current directory and "%PATH%" are replaced with
   "%COMSPEC%" and "%SystemRoot%\System32\cmd.exe". As a result,
   dropping a malicious program named "cmd.exe" into a current
   directory no longer works.

   *stdin*, *stdout* and *stderr* specify the executed program's
   standard input, standard output and standard error file handles,
   respectively.  Valid values are "PIPE", "DEVNULL", an existing file
   descriptor (a positive integer), an existing *file object* with a
   valid file descriptor, and "None".  "PIPE" indicates that a new
   pipe to the child should be created.  "DEVNULL" indicates that the
   special file "os.devnull" will be used. With the default settings
   of "None", no redirection will occur; the child's file handles will
   be inherited from the parent.  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 が呼ばれる前に子プロセ
     スがデッドロックを起こすことがあります。それを使用しなければなら
     ない場合、プログラムを自明なものにしておいてください! 呼び出すラ
     イブラリの数を最小にしてください。

   注釈:

     子プロセスのために環境を変更する必要がある場合は、*preexec_fn* の
     中でそれをするのではなく *env* 引数を使用します。
     *start_new_session* 引数は、子プロセスの中で os.setsid() を呼ぶ過
     去の一般的な *preexec_fn* の使用方法の代わりになります。

   バージョン 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.  In particular, 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* が追加されました。

   *start_new_session* が真の場合、サブプロセスの実行前に子プロセス内
   で setsid() システムコールが作成されます。(POSIX のみ)

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

   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)

   利用可能な環境: POSIX

   バージョン 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)

   利用可能な環境: POSIX

   バージョン 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)

   利用可能な環境: POSIX

   バージョン 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.

   利用可能な環境: POSIX

   バージョン 3.9 で追加.

   *env* が "None" 以外の場合、これは新しいプロセスでの環境変数を定義
   します。デフォルトでは、子プロセスは現在のプロセスの環境変数を引き
   継ぎます。

   注釈:

     *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 で追加: *encoding* と *errors* が追加されました。

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

   *startupinfo* は、基底の "CreateProcess" 関数に渡される
   "STARTUPINFO" オブジェクトになります。*creationflags* は、与えられ
   るなら、以下のフラグのうち一つ以上にできます:

      * "CREATE_NEW_CONSOLE"

      * "CREATE_NEW_PROCESS_GROUP"

      * "ABOVE_NORMAL_PRIORITY_CLASS"

      * "BELOW_NORMAL_PRIORITY_CLASS"

      * "HIGH_PRIORITY_CLASS"

      * "IDLE_PRIORITY_CLASS"

      * "NORMAL_PRIORITY_CLASS"

      * "REALTIME_PRIORITY_CLASS"

      * "CREATE_NO_WINDOW"

      * "DETACHED_PROCESS"

      * "CREATE_DEFAULT_ERROR_MODE"

      * "CREATE_BREAKAWAY_FROM_JOB"

   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" を送出しま
す。

"call()" や "Popen.communicate()" のような *timeout* 引数を受け取るす
べての関数とメソッドは、プロセスが終了する前にタイムアウトが発生した場
合に "TimeoutExpired" を送出します。

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

   バージョン 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.

"shell=True" を使用するときは、シェルコマンドで使用される文字列の空白
やメタ文字は "shlex.quote()" 関数を使うと正しくエスケープできます。

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()" を使用してください。

   注釈:

     この関数はビジーループ (非ブロック化呼び出しと短いスリープ) を使
     用して実装されています。非同期の待機には "asyncio" モジュールを使
     用してください ("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()

   子プロセスを停止します。POSIX OS では、このメソッドは SIGTERM シグ
   ナルを子プロセスに送ります。Windows では、Win32 API の
   "TerminateProcess()" 関数を利用して子プロセスを止めます。

Popen.kill()

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

以下の属性も利用可能です:

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 *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 *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 *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

   "poll()" か "wait()" (か、間接的に "communicate()") から設定された
   、子プロセスの終了ステータスが入ります。"None" はまだその子プロセス
   が終了していないことを示します。

   負の値 "-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

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

      バージョン 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.9.17 で変更: Changed Windows shell search order for
   "shell=True". The current directory and "%PATH%" are replaced with
   "%COMSPEC%" and "%SystemRoot%\System32\cmd.exe". As a result,
   dropping a malicious program named "cmd.exe" into a current
   directory no longer works.

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.9.17 で変更: Changed Windows shell search order for
   "shell=True". The current directory and "%PATH%" are replaced with
   "%COMSPEC%" and "%SystemRoot%\System32\cmd.exe". As a result,
   dropping a malicious program named "cmd.exe" into a current
   directory no longer works.

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.9.17 で変更: Changed Windows shell search order for
   "shell=True". The current directory and "%PATH%" are replaced with
   "%COMSPEC%" and "%SystemRoot%\System32\cmd.exe". As a result,
   dropping a malicious program named "cmd.exe" into a current
   directory no longer works.


古い関数を "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")


"popen2" モジュールの関数群を置き換える
---------------------------------------

注釈:

  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)

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

   Execute the string *cmd* in a shell with "Popen.check_output()" and
   return a 2-tuple "(exitcode, output)". The locale encoding is used;
   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, '')

   利用可能な環境: POSIX と 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".

subprocess.getoutput(cmd)

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

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

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

   利用可能な環境: POSIX と Windows。

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


注釈
====


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

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

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

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

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

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

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

参考:

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