<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](sched.xhtml "sched --- 事件調度器") | - [上一頁](concurrent.futures.xhtml "concurrent.futures --- 啟動并行任務") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [并發執行](concurrency.xhtml) ? - $('.inline-search').show(0); | # [`subprocess`](#module-subprocess "subprocess: Subprocess management.") --- 子進程管理 **源代碼:** [Lib/subprocess.py](https://github.com/python/cpython/tree/3.7/Lib/subprocess.py) \[https://github.com/python/cpython/tree/3.7/Lib/subprocess.py\] - - - - - - [`subprocess`](#module-subprocess "subprocess: Subprocess management.") 模塊允許你生成新的進程,連接它們的輸入、輸出、錯誤管道,并且獲取它們的返回碼。此模塊打算代替一些老舊的模塊與功能: ``` os.system os.spawn* ``` 在下面的段落中,你可以找到關于 [`subprocess`](#module-subprocess "subprocess: Subprocess management.") 模塊如何代替這些模塊和功能的相關信息。 參見 [**PEP 324**](https://www.python.org/dev/peps/pep-0324) \[https://www.python.org/dev/peps/pep-0324\] -- 提出 subprocess 模塊的 PEP ## 使用 [`subprocess`](#module-subprocess "subprocess: Subprocess management.") 模塊 推薦的調用子進程的方式是在任何它支持的用例中使用 [`run()`](#subprocess.run "subprocess.run") 函數。對于更進階的用例,也可以使用底層的 [`Popen`](#subprocess.Popen "subprocess.Popen") 接口。 [`run()`](#subprocess.run "subprocess.run") 函數是在 Python 3.5 被添加的;如果你需要與舊版本保持兼容,查看 [Older high-level API](#call-function-trio) 段落。 `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*)運行被 *arg* 描述的指令。等待指令完成,然后返回一個 [`CompletedProcess`](#subprocess.CompletedProcess "subprocess.CompletedProcess") 示例。 以上顯示的參數僅僅是最簡單的一些,下面 [常用參數](#frequently-used-arguments) 描述(因此在縮寫簽名中使用僅關鍵字標示)。完整的函數頭和 [`Popen`](#subprocess.Popen "subprocess.Popen") 的構造函數一樣,此函數接受的大多數參數都被傳遞給該接口。(*timeout*, *input*, *check* 和 *capture\_output* 除外)。 If *capture\_output* is true, stdout and stderr will be captured. When used, the internal [`Popen`](#subprocess.Popen "subprocess.Popen") object is automatically created with `stdout=PIPE` and `stderr=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, use `stdout=PIPE` and `stderr=STDOUT`instead of *capture\_output*. *timeout* 參數將被傳遞給 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate")。如果發生超時,子進程將被殺死并等待。 [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") 異常將在子進程中斷后被拋出。 *input* 參數將被傳遞給 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 以及子進程的標準輸入. 如果使用此參數, 它必須是一個字節序列. 如果指定了 *encoding* 或 *errors* 或者將 *text* 設置為 `True`, 那么也可以是一個字符串. 當使用此參數時, 內部的 [`Popen`](#subprocess.Popen "subprocess.Popen") 對象將自動被創建, 伴隨著設置 `stdin=PIPE`, 并且 *stdin* 可能不被使用. 如果 *check* 設為 True, 并且進程以非零狀態碼退出, 一個 [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") 異常將被拋出. 這個異常的屬性將設置為參數, 退出碼, 以及標準輸出和標準錯誤, 如果被捕獲到. 如果 *encoding* 或者 *error* 被指定, 或者 *text* 被設為 True, 標準輸入, 標準輸出和標準錯誤的文件對象將通過指定的 *encoding* 和 *errors* 以文本模式打開, 否則以默認的 [`io.TextIOWrapper`](io.xhtml#io.TextIOWrapper "io.TextIOWrapper") 打開. *universal\_newline* 參數等同于 *text* 并且提供了向后兼容性. 默認情況下, 文件對象是以二進制模式打開的. 如果 *env* 不是 `None`, 它必須是一個字典, 為新的進程設置環境變量; 它用于替換繼承的當前進程的環境的默認行為. 它將直接被傳遞給 [`Popen`](#subprocess.Popen "subprocess.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* 和 *errors* 形參. 在 3.7 版更改: 添加了 *text* 形參, 作為 *universal\_newlines* 的一個更好理解的別名. 添加了 *capture\_output* 形參. *class* `subprocess.``CompletedProcess`[`run()`](#subprocess.run "subprocess.run") 的返回值, 代表一個進程已經結束. `args`被用作啟動進程的參數. 可能是一個列表或字符串. `returncode`子進程的退出狀態碼. 通常來說, 一個為 0 的退出碼表示進程運行正常. 一個負值 `-N` 表示子進程被信號 `N` 中斷 (僅 POSIX). `stdout`從子進程捕獲到的標準輸出. 一個字節序列, 或一個字符串, 如果 [`run()`](#subprocess.run "subprocess.run") 是設置了 *encoding*, *errors* 或者 `text=True` 來運行的. 如果未有捕獲, 則為 `None`. 如果你通過 `stderr=subprocess.STDOUT` 運行, 標準輸入和標準錯誤將被組合在一起, 并且 `stderr`` 將為 `None`. `stderr`捕獲到的子進程的標準錯誤. 一個字節序列, 或者一個字符串, 如果 [`run()`](#subprocess.run "subprocess.run") 是設置了參數 *encoding*, *errors* 或者 `text=True` 運行的. 如果未有捕獲, 則為 `None`. `check_returncode`()如果 [`returncode`](#subprocess.CompletedProcess.returncode "subprocess.CompletedProcess.returncode") 非零, 拋出 [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError"). 3\.5 新版功能. `subprocess.``DEVNULL`可被 [`Popen`](#subprocess.Popen "subprocess.Popen") 的 *stdin*, *stdout* 或者 *stderr* 參數使用的特殊值, 表示使用特殊文件 [`os.devnull`](os.xhtml#os.devnull "os.devnull"). 3\.3 新版功能. `subprocess.``PIPE`可被 [`Popen`](#subprocess.Popen "subprocess.Popen") 的 *stdin*, *stdout* 或者 *stderr* 參數使用的特殊值, 表示打開標準流的管道. 常用于 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate"). `subprocess.``STDOUT`可被 [`Popen`](#subprocess.Popen "subprocess.Popen") 的 *stdin* , *stdout* 或者 *stderr* 參數使用的特殊值, 表示標準錯誤與標準輸出使用同一句柄。 *exception* `subprocess.``SubprocessError`此模塊的其他異常的基類。 3\.3 新版功能. *exception* `subprocess.``TimeoutExpired`[`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError") 的子類,等待子進程的過程中發生超時時被拋出。 `cmd`用于創建子進程的指令。 `timeout`超時秒數。 `output`子進程的輸出, 如果被 [`run()`](#subprocess.run "subprocess.run") 或 [`check_output()`](#subprocess.check_output "subprocess.check_output") 捕獲。否則為 `None`。 `stdout`對 output 的別名,對應的有 [`stderr`](#subprocess.TimeoutExpired.stderr "subprocess.TimeoutExpired.stderr")。 `stderr`子進程的標準錯誤輸出,如果被 [`run()`](#subprocess.run "subprocess.run") 捕獲。 否則為 `None`。 3\.3 新版功能. 在 3.5 版更改: 添加了 *stdout* 和 *stderr* 屬性。 *exception* `subprocess.``CalledProcessError`[`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError") 的子類,當一個被 [`check_call()`](#subprocess.check_call "subprocess.check_call") 或 [`check_output()`](#subprocess.check_output "subprocess.check_output") 函數運行的子進程返回了非零退出碼時被拋出。 `returncode`子進程的退出狀態。如果程序由一個信號終止,這將會被設為一個負的信號碼。 `cmd`用于創建子進程的指令。 `output`子進程的輸出, 如果被 [`run()`](#subprocess.run "subprocess.run") 或 [`check_output()`](#subprocess.check_output "subprocess.check_output") 捕獲。否則為 `None`。 `stdout`對 output 的別名,對應的有 [`stderr`](#subprocess.CalledProcessError.stderr "subprocess.CalledProcessError.stderr")。 `stderr`子進程的標準錯誤輸出,如果被 [`run()`](#subprocess.run "subprocess.run") 捕獲。 否則為 `None`。 在 3.5 版更改: 添加了 *stdout* 和 *stderr* 屬性。 ### 常用參數 為了支持豐富的使用案例, [`Popen`](#subprocess.Popen "subprocess.Popen") 的構造函數(以及方便的函數)接受大量可選的參數。對于大多數典型的用例,許多參數可以被安全地留以它們的默認值。通常需要的參數有: > *args* 被所有調用需要,應當為一個字符串,或者一個程序參數序列。提供一個參數序列通常更好,它可以更小心地使用參數中的轉義字符以及引用(例如允許文件名中的空格)。如果傳遞一個簡單的字符串,則 *shell* 參數必須為 [`True`](constants.xhtml#True "True") (見下文)或者該字符串中將被運行的程序名必須用簡單的命名而不指定任何參數。 > > *stdin*, *stdout* 和 *stderr* 分別指定了執行的程序的標準輸入、輸出和標準錯誤文件句柄。合法的值有 [`PIPE`](#subprocess.PIPE "subprocess.PIPE") 、 [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") 、 一個現存的文件描述符(一個正整數)、一個現存的文件對象以及 `None`。 [`PIPE`](#subprocess.PIPE "subprocess.PIPE") 表示應該新建一個對子進程的管道。 [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") 表示使用特殊的文件 [`os.devnull`](os.xhtml#os.devnull "os.devnull")。當使用默認設置 `None` 時,將不會進行重定向,子進程的文件流將繼承自父進程。另外, *stderr* 可能為 [`STDOUT`](#subprocess.STDOUT "subprocess.STDOUT"),表示來自于子進程的標準錯誤數據應該被 *stdout* 相同的句柄捕獲。 > > 如果 *encoding* 或 *errors* 被指定,或者 *text* (也名為 *universal\_newlines*)為真,則文件對象 *stdin* 、 *stdout* 與 *stderr* 將會使用在此次調用中指定的 *encoding* 和 *errors* 以文本模式打開或者為默認的 [`io.TextIOWrapper`](io.xhtml#io.TextIOWrapper "io.TextIOWrapper")。 > > 當構造函數的 *newline* 參數為 `None` 時。對于 *stdin*, 輸入的換行符 `'\n'` 將被轉換為默認的換行符 [`os.linesep`](os.xhtml#os.linesep "os.linesep")。對于 *stdout* 和 *stderr*, 所有輸出的換行符都被轉換為 `'\n'`。更多信息,查看 [`io.TextIOWrapper`](io.xhtml#io.TextIOWrapper "io.TextIOWrapper") 類的文檔。 > > 如果文本模式未被使用, *stdin*, *stdout* 和 *stderr* 將會以二進制流模式打開。沒有編碼與換行符轉換發生。 > > 3\.6 新版功能: 添加了 *encoding* 和 *errors* 形參。 > > > > 3\.7 新版功能: 添加了 *text* 形參作為 *universal\_newlines* 的別名。 > > > > 注解 > > 文件對象 [`Popen.stdin`](#subprocess.Popen.stdin "subprocess.Popen.stdin") 、 [`Popen.stdout`](#subprocess.Popen.stdout "subprocess.Popen.stdout") 和 [`Popen.stderr`](#subprocess.Popen.stderr "subprocess.Popen.stderr") 的換行符屬性不會被 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 方法更新。 > > > > 如果 *shell* 設為 `True`,,則使用 shell 執行指定的指令。如果您主要使用 Python 增強的控制流(它比大多數系統 shell 提供的強大),并且仍然希望方便地使用其他 shell 功能,如 shell 管道、文件通配符、環境變量展開以及 `~` 展開到用戶家目錄,這將非常有用。但是,注意 Python 自己也實現了許多類似 shell 的特性(例如 [`glob`](glob.xhtml#module-glob "glob: Unix shell style pathname pattern expansion."), [`fnmatch`](fnmatch.xhtml#module-fnmatch "fnmatch: Unix shell style filename pattern matching."), [`os.walk()`](os.xhtml#os.walk "os.walk"), [`os.path.expandvars()`](os.path.xhtml#os.path.expandvars "os.path.expandvars"), [`os.path.expanduser()`](os.path.xhtml#os.path.expanduser "os.path.expanduser") 和 [`shutil`](shutil.xhtml#module-shutil "shutil: High-level file operations, including copying."))。 > > 在 3.3 版更改: 當 *universal\_newline* 被設為 `True`,則類使用 [`locale.getpreferredencoding(False)`](locale.xhtml#locale.getpreferredencoding "locale.getpreferredencoding") 編碼來代替 `locale.getpreferredencoding()`。關于它們的區別的更多信息,見 [`io.TextIOWrapper`](io.xhtml#io.TextIOWrapper "io.TextIOWrapper")。 > > > > 注解 > > 在使用 `shell=True` 之前, 請閱讀 [Security Considerations](#security-considerations) 段落。 這些選項以及所有其他選項在 [`Popen`](#subprocess.Popen "subprocess.Popen") 構造函數文檔中有更詳細的描述。 ### Popen 構造函數 此模塊的底層的進程創建與管理由 [`Popen`](#subprocess.Popen "subprocess.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=()*, *\**, *encoding=None*, *errors=None*, *text=None*)在一個新的進程中執行子程序。在 POSIX,此類使用類似于 [`os.execvp()`](os.xhtml#os.execvp "os.execvp") 的行為來執行子程序。在 Windows,此類使用了 Windows `CreateProcess()` 函數。 [`Popen`](#subprocess.Popen "subprocess.Popen") 的參數如下: *args* 應當是一個程序的參數列表或者一個簡單的字符串。默認情況下,如果 *args* 是一個序列,將運行的程序是此序列的第一項。如果 *args* 是一個字符串,解釋是平臺相關的,如下所述。有關默認行為的其他差異,見 *shell* 和 *executable* 參數。除非另有說明,推薦將 *args* 作為序列傳遞。 在 POSIX,如果 *args* 是一個字符串,此字符串被作為將被執行的程序的命名或路徑解釋。但是,只有在不傳遞任何參數給程序的情況下才能這么做。 注解 [`shlex.split()`](shlex.xhtml#shlex.split "shlex.split") 在確定正確 *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! ``` 特別注意,由 shell 中的空格分隔的選項(例如 *-input*)和參數(例如 *eggs.txt* )位于分開的列表元素中,而在需要時使用引號或反斜杠轉義的參數在 shell (例如包含空格的文件名或上面顯示的 *echo* 命令)是單獨的列表元素。 在 Windows,如果 *args* 是一個序列,他將通過一個在 [Converting an argument sequence to a string on Windows](#converting-argument-sequence) 描述的方式被轉換為一個字符串。這是因為底層的 `CreateProcess()` 只處理字符串。 參數 *shell* (默認為 `False`)指定是否使用 shell 執行程序。如果 *shell* 為 `True`,更推薦將 *args* 作為字符串傳遞而非序列。 在 POSIX,當 `shell=True`, shell 默認為 `/bin/sh`。如果 *args* 是一個字符串,此字符串指定將通過 shell 執行的命令。這意味著字符串的格式必須和在命令提示符中所輸入的完全相同。這包括,例如,引號和反斜杠轉義包含空格的文件名。如果 *args* 是一個序列,第一項指定了命令,另外的項目將作為傳遞給 shell (而非命令) 的參數對待。也就是說, [`Popen`](#subprocess.Popen "subprocess.Popen") 等同于: ``` Popen(['/bin/sh', '-c', args[0], args[1], ...]) ``` 在 Windows,使用 `shell=True`,環境變量 `COMSPEC` 指定了默認 shell。在 Windows 你唯一需要指定 `shell=True` 的情況是你想要執行內置在 shell 中的命令(例如 **dir** 或者 **copy**)。在運行一個批處理文件或者基于控制臺的可執行文件時,不需要 `shell=True`。 注解 在使用 `shell=True` 之前, 請閱讀 [Security Considerations](#security-considerations) 段落。 *bufsize* 將在 [`open()`](functions.xhtml#open "open") 函數創建了 stdin/stdout/stderr 管道文件對象時作為對應的參數供應: - `0` 表示不使用緩沖區 (讀取與寫入是一個系統調用并且可以返回短內容) - `1` 表示行緩沖(只有 `universal_newlines=True` 時才有用,例如,在文本模式中) - 任何其他正值表示使用一個約為對應大小的緩沖區 - 負的 *bufsize* (默認)表示使用系統默認的 io.DEFAULT\_BUFFER\_SIZE。 在 3.3.1 版更改: *bufsize* 現在默認為 -1 來啟用緩沖,以符合大多數代碼所期望的行為。在 Python 3.2.4 和 3.3.1 之前的版本中,它錯誤地將默認值設為了為 `0`,這是無緩沖的并且允許短讀取。這是無意的,并且與大多數代碼所期望的 Python 2 的行為不一致。 *executable* 參數指定一個要執行的替換程序。這很少需要。當 `shell=True`, *executable* 替換 *args* 指定運行的程序。但是,原始的 *args* 仍然被傳遞給程序。大多數程序將被 *args* 指定的程序作為命令名對待,這可以與實際運行的程序不同。在 POSIX, *args* 名作為實際調用程序中可執行文件的顯示名稱,例如 **ps**。如果 `shell=True`,在 POSIX, *executable* 參數指定用于替換默認 shell `/bin/sh` 的 shell。 *stdin*, *stdout* 和 *stderr* 分別指定被運行的程序的標準輸入、輸出和標準錯誤的文件句柄。合法的值有 [`PIPE`](#subprocess.PIPE "subprocess.PIPE") , [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") , 一個存在的文件描述符(一個正整數),一個存在的 [文件對象](../glossary.xhtml#term-file-object) 以及 `None`。 [`PIPE`](#subprocess.PIPE "subprocess.PIPE") 表示應創建一個新的對子進程的管道。 [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") 表示使用特殊的 [`os.devnull`](os.xhtml#os.devnull "os.devnull") 文件。使用默認的 `None`,則不進行成定向;子進程的文件流將繼承自父進程。另外, *stderr* 可設為 [`STDOUT`](#subprocess.STDOUT "subprocess.STDOUT"),表示應用程序的標準錯誤數據應和標準輸出一同捕獲。 如果 *preexec\_fn* 被設為一個可調用對象,此對象將在子進程剛創建時被調用。(僅 POSIX) 警告 *preexec\_fn* 形參在應用程序中存在多線程時是不安全的。子進程在調用前可能死鎖。如果你必須使用它,保持警惕!最小化你調用的庫的數量。 注解 如果你需要修改子進程環境,使用 *env* 形參而非在 *preexec\_fn* 中進行。 *start\_new\_session* 形參可以代替之前常用的 *preexec\_fn* 來在子進程中調用 os.setsid()。 如果 *close\_fds* 為真,所有文件描述符除了 `0`, `1`, `2` 之外都會在子進程執行前關閉。而當 *close\_fds* 為假時,文件描述符遵守它們繼承的標志,如 [Inheritance of File Descriptors](os.xhtml#fd-inheritance) 所述。 在 Windows,如果 *close\_fds* 為真, 則子進程不會繼承任何句柄,除非在 `STARTUPINFO.IpAttributeList` 的 `handle_list` 的鍵中顯式傳遞,或者通過標準句柄重定向傳遞。 在 3.2 版更改: *close\_fds* 的默認值已經從 [`False`](constants.xhtml#False "False") 修改為上述值。 在 3.7 版更改: 在 Windows,當重定向標準句柄時 *close\_fds* 的默認值從 [`False`](constants.xhtml#False "False") 變為 [`True`](constants.xhtml#True "True")。現在重定向標準句柄時有可能設置 *close\_fds* 為 [`True`](constants.xhtml#True "True")。(標準句柄指三個 stdio 的句柄) *pass\_fds* 是一個可選的在父子進程間保持打開的文件描述符序列。提供任何 *pass\_fds* 將強制 *close\_fds* 為 [`True`](constants.xhtml#True "True")。(僅 POSIX) 3\.2 新版功能: 加入了 *pass\_fds* 形參。 如果 *cwd* 不為 `None`,此函數在執行子進程前改變當前工作目錄為 *cwd*。 *cwd* 可以為一個 [`str`](stdtypes.xhtml#str "str") 和 [path-like](../glossary.xhtml#term-path-like-object) 對象。特別要注意,當可執行文件的路徑為相對路徑時,此函數按相對于 *cwd* 的路徑來尋找 *executable* (或者 *args* 的第一項)。 在 3.6 版更改: *cwd* 形參接受一個 [path-like object](../glossary.xhtml#term-path-like-object)。 如果 *restore\_signals* 為 true(默認值),則 Python 設置為 SIG\_IGN 的所有信號將在 exec 之前的子進程中恢復為 SIG\_DFL。目前,這包括 SIGPIPE ,SIGXFZ 和 SIGXFSZ 信號。 (僅 POSIX) 在 3.2 版更改: *restore\_signals* 被加入。 如果 *start\_new\_session* 為 true,則 setsid() 系統調用將在子進程執行之前被執行。(僅 POSIX) 在 3.2 版更改: *start\_new\_session* 被添加。 如果 *env* 不為 `None`,則必須為一個為新進程定義了環境變量的字典;這些用于替換繼承的當前進程環境的默認行為。 注解 如果指定, *env* 必須提供所有被子進程需求的變量。在 Windows,為了運行一個 [side-by-side assembly](https://en.wikipedia.org/wiki/Side-by-Side_Assembly) \[https://en.wikipedia.org/wiki/Side-by-Side\_Assembly\] ,指定的 *env* **必須** 包含一個有效的 `SystemRoot`。 如果 *encoding* 或 *errors* 被指定,或者 *text* 為 true,則文件對象 *stdin*, *stdout* 和 *stderr* 將會以指定的編碼和 *errors* 以文本模式打開,如同 [常用參數](#frequently-used-arguments) 所述。 *universal\_newlines* 參數等同于 *text* 并且提供向后兼容性。默認情況下,文件對象都以二進制模式打開。 3\.6 新版功能: *encoding* 和 *errors* 被添加。 3\.7 新版功能: *text* 作為 *universal\_newlines* 的一個更具可讀性的別名被添加。 如果給出, *startupinfo* 將是一個將被傳遞給底層的 `CreateProcess` 函數的 [`STARTUPINFO`](#subprocess.STARTUPINFO "subprocess.STARTUPINFO") 對象。 *creationflags*,如果給出,可以是一個或多個以下標志之一: > - [`CREATE_NEW_CONSOLE`](#subprocess.CREATE_NEW_CONSOLE "subprocess.CREATE_NEW_CONSOLE") > - [`CREATE_NEW_PROCESS_GROUP`](#subprocess.CREATE_NEW_PROCESS_GROUP "subprocess.CREATE_NEW_PROCESS_GROUP") > - [`ABOVE_NORMAL_PRIORITY_CLASS`](#subprocess.ABOVE_NORMAL_PRIORITY_CLASS "subprocess.ABOVE_NORMAL_PRIORITY_CLASS") > - [`BELOW_NORMAL_PRIORITY_CLASS`](#subprocess.BELOW_NORMAL_PRIORITY_CLASS "subprocess.BELOW_NORMAL_PRIORITY_CLASS") > - [`HIGH_PRIORITY_CLASS`](#subprocess.HIGH_PRIORITY_CLASS "subprocess.HIGH_PRIORITY_CLASS") > - [`IDLE_PRIORITY_CLASS`](#subprocess.IDLE_PRIORITY_CLASS "subprocess.IDLE_PRIORITY_CLASS") > - [`NORMAL_PRIORITY_CLASS`](#subprocess.NORMAL_PRIORITY_CLASS "subprocess.NORMAL_PRIORITY_CLASS") > - [`REALTIME_PRIORITY_CLASS`](#subprocess.REALTIME_PRIORITY_CLASS "subprocess.REALTIME_PRIORITY_CLASS") > - [`CREATE_NO_WINDOW`](#subprocess.CREATE_NO_WINDOW "subprocess.CREATE_NO_WINDOW") > - [`DETACHED_PROCESS`](#subprocess.DETACHED_PROCESS "subprocess.DETACHED_PROCESS") > - [`CREATE_DEFAULT_ERROR_MODE`](#subprocess.CREATE_DEFAULT_ERROR_MODE "subprocess.CREATE_DEFAULT_ERROR_MODE") > - [`CREATE_BREAKAWAY_FROM_JOB`](#subprocess.CREATE_BREAKAWAY_FROM_JOB "subprocess.CREATE_BREAKAWAY_FROM_JOB") Popen 對象支持通過 [`with`](../reference/compound_stmts.xhtml#with) 語句作為上下文管理器,在退出時關閉文件描述符并等待進程: ``` with Popen(["ifconfig"], stdout=PIPE) as proc: log.write(proc.stdout.read()) ``` 在 3.2 版更改: 添加了上下文管理器支持。 在 3.6 版更改: 現在,如果 Popen 析構時子進程仍然在運行,則析構器會發送一個 [`ResourceWarning`](exceptions.xhtml#ResourceWarning "ResourceWarning") 警告。 ### 異常 在子進程中拋出的異常,在新的進程開始執行前,將會被再次在父進程中拋出。 最常見的被拋出異常是 [`OSError`](exceptions.xhtml#OSError "OSError")。例如,當嘗試執行一個不存在的文件時就會發生。應用程序需要為 [`OSError`](exceptions.xhtml#OSError "OSError") 異常做好準備。 如果 [`Popen`](#subprocess.Popen "subprocess.Popen") 調用時有無效的參數,則一個 [`ValueError`](exceptions.xhtml#ValueError "ValueError") 將被拋出。 `check_all()` 與 [`check_output()`](#subprocess.check_output "subprocess.check_output") 在調用的進程返回非零退出碼時將拋出 [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError")。 所有接受 *timeout* 形參的函數與方法,例如 [`call()`](#subprocess.call "subprocess.call") 和 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 將會在進程退出前超時到期時拋出 [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired")。 此模塊中定義的異常都繼承自 [`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError")。 > 3\.3 新版功能: 基類 [`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError") 被添加。 ## 安全考量 不像一些其他的 popen 功能,此實現絕不會隱式調用一個系統 shell。這意味著任何字符,包括 shell 元字符,可以安全地被傳遞給子進程。如果 shell 被明確地調用,通過 `shell=True` 設置,則確保所有空白字符和元字符被恰當地包裹在引號內以避免 [shell 注入](https://en.wikipedia.org/wiki/Shell_injection#Shell_injection) \[https://en.wikipedia.org/wiki/Shell\_injection#Shell\_injection\] 漏洞就由應用程序負責了。 當使用 `shell=True`, [`shlex.quote()`](shlex.xhtml#shlex.quote "shlex.quote") 函數可以作為在將被用于構造 shell 指令的字符串中轉義空白字符以及 shell 元字符的方案。 ## Popen 對象 [`Popen`](#subprocess.Popen "subprocess.Popen") 類的實例擁有以下方法: `Popen.``poll`()檢查子進程是否已被終止。設置并返回 [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") 屬性。否則返回 `None`。 `Popen.``wait`(*timeout=None*)等待子進程被終止。設置并返回 [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") 屬性。 如果進程在 *timeout* 秒后未中斷,拋出一個 [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") 異常,可以安全地捕獲此異常并重新等待。 注解 當 `stdout=PIPE` 或者 `stderr=PIPE` 并且子進程產生了足以阻塞 OS 管道緩沖區接收更多數據的輸出到管道時,將會發生死鎖。當使用管道時用 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 來規避它。 注解 此函數使用了一個 busy loop (非阻塞調用以及短睡眠) 實現。使用 [`asyncio`](asyncio.xhtml#module-asyncio "asyncio: Asynchronous I/O.") 模塊進行異步等待: 參閱 [`asyncio.create_subprocess_exec`](asyncio-subprocess.xhtml#asyncio.create_subprocess_exec "asyncio.create_subprocess_exec")。 在 3.3 版更改: *timeout* 被添加 `Popen.``communicate`(*input=None*, *timeout=None*)與進程交互:向 stdin 傳輸數據。從 stdout 和 stderr 讀取數據,直到文件結束符。等待進程終止。可選的 *input* 參數應當未被傳輸給子進程的數據,如果沒有數據應被傳輸給子進程則為 `None`。如果流以文本模式打開, *input* 必須為字符串。否則,它必須為字節。 [`communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 返回一個 `(stdout_data, stderr_data)` 元組。如果文件以文本模式打開則為字符串;否則字節。 注意如果你想要向進程的 stdin 傳輸數據,你需要通過 `stdin=PIPE` 創建此 Popen 對象。類似的,要從結果元組獲取任何非 `None` 值,你同樣需要設置 `stdout=PIPE` 或者 `stderr=PIPE`。 如果進程在 *timeout* 秒后未終止,一個 [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") 異常將被拋出。捕獲此異常并重新等待將不會丟失任何輸出。 如果超時到期,子進程不會被殺死,所以為了正確清理一個行為良好的應用程序應該殺死子進程并完成通訊。 ``` 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* 發送給子進程。 注解 在 Windows, SIGTERM 是一個 [`terminate()`](#subprocess.Popen.terminate "subprocess.Popen.terminate") 的別名。 CTRL\_C\_EVENT 和 CTRL\_BREAK\_EVENT 可以被發送給以包含 `CREATE_NEW_PROCESS` 的 *creationflags* 形參啟動的進程。 `Popen.``terminate`()停止子進程。在 Posix 操作系統上,此方法發送 SIGTERM。在 Windows,調用 Win32 API 函數 `TerminateProcess()` 來停止子進程。 `Popen.``kill`()殺死子進程。在 Posix 操作系統上,此函數給子進程發送 SIGKILL 信號。在 Windows 上, [`kill()`](#subprocess.Popen.kill "subprocess.Popen.kill") 是 [`terminate()`](#subprocess.Popen.terminate "subprocess.Popen.terminate") 的別名。 以下屬性也是可用的: `Popen.``args`*args* 參數傳遞給 [`Popen`](#subprocess.Popen "subprocess.Popen") -- 一個程序參數的序列或者一個簡單字符串。 3\.3 新版功能. `Popen.``stdin`如果 *stdin* 參數為 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此屬性是一個類似 [`open()`](functions.xhtml#open "open") 返回的可寫的流對象。如果 *encoding* 或 *errors* 參數被指定或者 *universal\_newlines* 參數為 `True`,則此流是一個文本流,否則是字節流。如果 *stdin* 參數非 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), 此屬性為 `None`。 `Popen.``stdout`如果 *stdout* 參數是 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此屬性是一個類似 [`open()`](functions.xhtml#open "open") 返回的可讀流。從流中讀取子進程提供的輸出。如果 *encoding* 或 *errors* 參數被指定或者 *universal\_newlines* 參數為 `True`,此流為文本流,否則為字節流。如果 *stdout* 參數非 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此屬性為 `None`。 `Popen.``stderr`如果 *stderr* 參數是 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此屬性是一個類似 [`open()`](functions.xhtml#open "open") 返回的可讀流。從流中讀取子進程提供的輸出。如果 *encoding* 或 *errors* 參數被指定或者 *universal\_newlines* 參數為 `True`,此流為文本流,否則為字節流。如果 *stderr* 參數非 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此屬性為 `None`。 警告 使用 [`communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 而非 [`.stdin.write`](#subprocess.Popen.stdin "subprocess.Popen.stdin"), [`.stdout.read`](#subprocess.Popen.stdout "subprocess.Popen.stdout") 或者 [`.stderr.read`](#subprocess.Popen.stderr "subprocess.Popen.stderr") 來避免由于任意其他 OS 管道緩沖區被子進程填滿阻塞而導致的死鎖。 `Popen.``pid`子進程的進程號。 注意如果你設置了 *shell* 參數為 `True`,則這是生成的子 shell 的進程號。 `Popen.``returncode`此進程的退出碼,由 [`poll()`](#subprocess.Popen.poll "subprocess.Popen.poll") 和 [`wait()`](#subprocess.Popen.wait "subprocess.Popen.wait") 設置(以及直接由 [`communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 設置)。一個 `None` 值 表示此進程仍未結束。 一個負值 `-N` 表示子進程被信號 `N` 中斷 (僅 POSIX). ## Windows Popen 助手 [`STARTUPINFO`](#subprocess.STARTUPINFO "subprocess.STARTUPINFO") 類和以下常數僅在 Windows 有效。 *class* `subprocess.``STARTUPINFO`(*\**, *dwFlags=0*, *hStdInput=None*, *hStdOutput=None*, *hStdError=None*, *wShowWindow=0*, *lpAttributeList=None*)在 [`Popen`](#subprocess.Popen "subprocess.Popen") 創建時部分支持 Windows 的 [STARTUPINFO](https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx) \[https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx\] 結構。接下來的屬性僅能通過關鍵詞參數設置。 在 3.7 版更改: 僅關鍵詞參數支持被加入。 `dwFlags`A bit field that determines whether certain [`STARTUPINFO`](#subprocess.STARTUPINFO "subprocess.STARTUPINFO")attributes are used when the process creates a window. ``` si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW ``` `hStdInput`If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES"), this attribute is the standard input handle for the process. If [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES") is not specified, the default for standard input is the keyboard buffer. `hStdOutput`If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES"), this attribute is the standard output handle for the process. Otherwise, this attribute is ignored and the default for standard output is the console window's buffer. `hStdError`If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES"), this attribute is the standard error handle for the process. Otherwise, this attribute is ignored and the default for standard error is the console window's buffer. `wShowWindow`If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESHOWWINDOW`](#subprocess.STARTF_USESHOWWINDOW "subprocess.STARTF_USESHOWWINDOW"), this attribute can be any of the values that can be specified in the `nCmdShow`parameter for the [ShowWindow](https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx) \[https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx\]function, except for `SW_SHOWDEFAULT`. Otherwise, this attribute is ignored. [`SW_HIDE`](#subprocess.SW_HIDE "subprocess.SW_HIDE") is provided for this attribute. It is used when [`Popen`](#subprocess.Popen "subprocess.Popen") is called with `shell=True`. `lpAttributeList`A dictionary of additional attributes for process creation as given in `STARTUPINFOEX`, see [UpdateProcThreadAttribute](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx) \[https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx\]. 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()`](os.xhtml#os.set_handle_inheritable "os.set_handle_inheritable") when passed to the [`Popen`](#subprocess.Popen "subprocess.Popen")constructor, else [`OSError`](exceptions.xhtml#OSError "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()`](os.xhtml#os.system "os.system"). This also applies to standard handle redirection, which temporarily creates inheritable handles. 3\.7 新版功能. ### Windows Constants The [`subprocess`](#module-subprocess "subprocess: Subprocess management.") module exposes the following constants. `subprocess.``STD_INPUT_HANDLE`The standard input device. Initially, this is the console input buffer, `CONIN$`. `subprocess.``STD_OUTPUT_HANDLE`The standard output device. Initially, this is the active console screen buffer, `CONOUT$`. `subprocess.``STD_ERROR_HANDLE`The standard error device. Initially, this is the active console screen buffer, `CONOUT$`. `subprocess.``SW_HIDE`Hides the window. Another window will be activated. `subprocess.``STARTF_USESTDHANDLES`Specifies that the [`STARTUPINFO.hStdInput`](#subprocess.STARTUPINFO.hStdInput "subprocess.STARTUPINFO.hStdInput"), [`STARTUPINFO.hStdOutput`](#subprocess.STARTUPINFO.hStdOutput "subprocess.STARTUPINFO.hStdOutput"), and [`STARTUPINFO.hStdError`](#subprocess.STARTUPINFO.hStdError "subprocess.STARTUPINFO.hStdError") attributes contain additional information. `subprocess.``STARTF_USESHOWWINDOW`Specifies that the [`STARTUPINFO.wShowWindow`](#subprocess.STARTUPINFO.wShowWindow "subprocess.STARTUPINFO.wShowWindow") attribute contains additional information. `subprocess.``CREATE_NEW_CONSOLE`The new process has a new console, instead of inheriting its parent's console (the default). `subprocess.``CREATE_NEW_PROCESS_GROUP`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process group will be created. This flag is necessary for using [`os.kill()`](os.xhtml#os.kill "os.kill")on the subprocess. This flag is ignored if [`CREATE_NEW_CONSOLE`](#subprocess.CREATE_NEW_CONSOLE "subprocess.CREATE_NEW_CONSOLE") is specified. `subprocess.``ABOVE_NORMAL_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have an above average priority. 3\.7 新版功能. `subprocess.``BELOW_NORMAL_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have a below average priority. 3\.7 新版功能. `subprocess.``HIGH_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have a high priority. 3\.7 新版功能. `subprocess.``IDLE_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have an idle (lowest) priority. 3\.7 新版功能. `subprocess.``NORMAL_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have an normal priority. (default) 3\.7 新版功能. `subprocess.``REALTIME_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.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`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will not create a window. 3\.7 新版功能. `subprocess.``DETACHED_PROCESS`A [`Popen`](#subprocess.Popen "subprocess.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`](#subprocess.Popen "subprocess.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`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process is not associated with the job. 3\.7 新版功能. ## Older high-level API Prior to Python 3.5, these three functions comprised the high level API to subprocess. You can now use [`run()`](#subprocess.run "subprocess.run") in many cases, but lots of existing code calls these functions. `subprocess.``call`(*args*, *\**, *stdin=None*, *stdout=None*, *stderr=None*, *shell=False*, *cwd=None*, *timeout=None*)Run the command described by *args*. Wait for command to complete, then return the [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") attribute. Code needing to capture stdout or stderr should use [`run()`](#subprocess.run "subprocess.run") instead: > run(...).returncode To suppress stdout or stderr, supply a value of [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL"). The arguments shown above are merely some common ones. The full function signature is the same as that of the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor - this function passes all supplied arguments other than *timeout* directly through to that interface. 注解 Do not use `stdout=PIPE` or `stderr=PIPE` with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. 在 3.3 版更改: *timeout* 被添加 `subprocess.``check_call`(*args*, *\**, *stdin=None*, *stdout=None*, *stderr=None*, *shell=False*, *cwd=None*, *timeout=None*)Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError"). The [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") object will have the return code in the [`returncode`](#subprocess.CalledProcessError.returncode "subprocess.CalledProcessError.returncode") attribute. Code needing to capture stdout or stderr should use [`run()`](#subprocess.run "subprocess.run") instead: > run(..., check=True) To suppress stdout or stderr, supply a value of [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL"). The arguments shown above are merely some common ones. The full function signature is the same as that of the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor - this function passes all supplied arguments other than *timeout* directly through to that interface. 注解 Do not use `stdout=PIPE` or `stderr=PIPE` with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. 在 3.3 版更改: *timeout* 被添加 `subprocess.``check_output`(*args*, *\**, *stdin=None*, *stderr=None*, *shell=False*, *cwd=None*, *encoding=None*, *errors=None*, *universal\_newlines=None*, *timeout=None*, *text=None*)Run command with arguments and return its output. If the return code was non-zero it raises a [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError"). The [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") object will have the return code in the [`returncode`](#subprocess.CalledProcessError.returncode "subprocess.CalledProcessError.returncode") attribute and any output in the [`output`](#subprocess.CalledProcessError.output "subprocess.CalledProcessError.output") attribute. This is equivalent to: ``` 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()`](#subprocess.run "subprocess.run") - most arguments are passed directly through to that interface. However, explicitly passing `input=None` to inherit the parent's standard input file handle is not supported. By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level. This behaviour may be overridden by setting *text*, *encoding*, *errors*, or *universal\_newlines* to `True` as described in [常用參數](#frequently-used-arguments) and [`run()`](#subprocess.run "subprocess.run"). To also capture standard error in the result, use `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 版更改: Support for the *input* keyword argument was added. 在 3.6 版更改: *encoding* and *errors* were added. See [`run()`](#subprocess.run "subprocess.run") for details. 3\.7 新版功能: *text* 作為 *universal\_newlines* 的一個更具可讀性的別名被添加。 ## Replacing Older Functions with the [`subprocess`](#module-subprocess "subprocess: Subprocess management.") Module In this section, "a becomes b" means that b can be used as a replacement for a. 注解 All "a" functions in this section fail (more or less) silently if the executed program cannot be found; the "b" replacements raise [`OSError`](exceptions.xhtml#OSError "OSError")instead. In addition, the replacements using [`check_output()`](#subprocess.check_output "subprocess.check_output") will fail with a [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") if the requested operation produces a non-zero return code. The output is still available as the [`output`](#subprocess.CalledProcessError.output "subprocess.CalledProcessError.output") attribute of the raised exception. In the following examples, we assume that the relevant functions have already been imported from the [`subprocess`](#module-subprocess "subprocess: Subprocess management.") module. ### Replacing /bin/sh shell backquote ``` output=`mycmd myarg` ``` becomes: ``` output = check_output(["mycmd", "myarg"]) ``` ### Replacing shell pipeline ``` output=`dmesg | grep hda` ``` becomes: ``` 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] ``` The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1. Alternatively, for trusted input, the shell's own pipeline support may still be used directly: ``` output=`dmesg | grep hda` ``` becomes: ``` output=check_output("dmesg | grep hda", shell=True) ``` ### Replacing [`os.system()`](os.xhtml#os.system "os.system") ``` sts = os.system("mycmd" + " myarg") # becomes sts = call("mycmd" + " myarg", shell=True) ``` 注釋: - Calling the program through the shell is usually not required. A more realistic example would look like this: ``` 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) ``` ### Replacing the [`os.spawn`](os.xhtml#os.spawnl "os.spawnl") family P\_NOWAIT example: ``` pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid ``` P\_WAIT example: ``` retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) ``` Vector example: ``` os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) ``` Environment example: ``` os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) ``` ### Replacing [`os.popen()`](os.xhtml#os.popen "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) ``` Return code handling translates as follows: ``` 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 注解 If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. ``` (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` and `popen2.Popen4` basically work as [`subprocess.Popen`](#subprocess.Popen "subprocess.Popen"), except that: - [`Popen`](#subprocess.Popen "subprocess.Popen") raises an exception if the execution fails. - The *capturestderr* argument is replaced with the *stderr* argument. - `stdin=PIPE` and `stdout=PIPE` must be specified. - popen2 closes all file descriptors by default, but you have to specify `close_fds=True` with [`Popen`](#subprocess.Popen "subprocess.Popen") to guarantee this behavior on all platforms or past Python versions. ## Legacy Shell Invocation Functions This module also provides the following legacy functions from the 2.x `commands` module. These operations implicitly invoke the system shell and none of the guarantees described above regarding security and exception handling consistency are valid for these functions. `subprocess.``getstatusoutput`(*cmd*)Return `(exitcode, output)` of executing *cmd* in a shell. 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 [常用參數](#frequently-used-arguments) 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](intro.xhtml#availability): POSIX & Windows. 在 3.3.4 版更改: Windows support was added. 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.Popen.returncode "subprocess.Popen.returncode"). `subprocess.``getoutput`(*cmd*)Return output (stdout and stderr) of executing *cmd* in a shell. Like [`getstatusoutput()`](#subprocess.getstatusoutput "subprocess.getstatusoutput"), except the exit code is ignored and the return value is a string containing the command's output. Example: ``` >>> subprocess.getoutput('ls /bin/ls') '/bin/ls' ``` [Availability](intro.xhtml#availability): POSIX & Windows. 在 3.3.4 版更改: Windows support added ## 注釋 ### Converting an argument sequence to a string on Windows On Windows, an *args* sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime): 1. Arguments are delimited by white space, which is either a space or a tab. 2. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3. A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4. Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5. If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. 參見 [`shlex`](shlex.xhtml#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.")Module which provides function to parse and escape command lines. ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](sched.xhtml "sched --- 事件調度器") | - [上一頁](concurrent.futures.xhtml "concurrent.futures --- 啟動并行任務") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [并發執行](concurrency.xhtml) ? - $('.inline-search').show(0); | ? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看