### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](sched.xhtml "sched --- 事件調度器") |
- [上一頁](concurrent.futures.xhtml "concurrent.futures --- 啟動并行任務") |
- 
- [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 --- 啟動并行任務") |
- 
- [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 創建。
- Python文檔內容
- Python 有什么新變化?
- Python 3.7 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- C API 的改變
- 構建的改變
- 性能優化
- 其他 CPython 實現的改變
- 已棄用的 Python 行為
- 已棄用的 Python 模塊、函數和方法
- 已棄用的 C API 函數和類型
- 平臺支持的移除
- API 與特性的移除
- 移除的模塊
- Windows 專屬的改變
- 移植到 Python 3.7
- Python 3.7.1 中的重要變化
- Python 3.7.2 中的重要變化
- Python 3.6 有什么新變化A
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 其他改進
- 棄用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要變化
- Python 3.6.4 中的重要變化
- Python 3.6.5 中的重要變化
- Python 3.6.7 中的重要變化
- Python 3.5 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- Other module-level changes
- 性能優化
- Build and C API Changes
- 棄用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 發布重點
- 新的特性
- 新增模塊
- 改進的模塊
- CPython Implementation Changes
- 棄用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 發布重點
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他語言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 棄用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 多線程
- 性能優化
- Unicode
- Codecs
- 文檔
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 性能優化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他語言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新變化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他語言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他語言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推導式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最終版
- Python 3.7.3 發布候選版 1
- Python 3.7.2 最終版
- Python 3.7.2 發布候選版 1
- Python 3.7.1 最終版
- Python 3.7.1 RC 2版本
- Python 3.7.1 發布候選版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 課前甜點
- 使用 Python 解釋器
- 調用解釋器
- 解釋器的運行環境
- Python 的非正式介紹
- Python 作為計算器使用
- 走向編程的第一步
- 其他流程控制工具
- if 語句
- for 語句
- range() 函數
- break 和 continue 語句,以及循環中的 else 子句
- pass 語句
- 定義函數
- 函數定義的更多形式
- 小插曲:編碼風格
- 數據結構
- 列表的更多特性
- del 語句
- 元組和序列
- 集合
- 字典
- 循環的技巧
- 深入條件控制
- 序列和其它類型的比較
- 模塊
- 有關模塊的更多信息
- 標準模塊
- dir() 函數
- 包
- 輸入輸出
- 更漂亮的輸出格式
- 讀寫文件
- 錯誤和異常
- 語法錯誤
- 異常
- 處理異常
- 拋出異常
- 用戶自定義異常
- 定義清理操作
- 預定義的清理操作
- 類
- 名稱和對象
- Python 作用域和命名空間
- 初探類
- 補充說明
- 繼承
- 私有變量
- 雜項說明
- 迭代器
- 生成器
- 生成器表達式
- 標準庫簡介
- 操作系統接口
- 文件通配符
- 命令行參數
- 錯誤輸出重定向和程序終止
- 字符串模式匹配
- 數學
- 互聯網訪問
- 日期和時間
- 數據壓縮
- 性能測量
- 質量控制
- 自帶電池
- 標準庫簡介 —— 第二部分
- 格式化輸出
- 模板
- 使用二進制數據記錄格式
- 多線程
- 日志
- 弱引用
- 用于操作列表的工具
- 十進制浮點運算
- 虛擬環境和包
- 概述
- 創建虛擬環境
- 使用pip管理包
- 接下來?
- 交互式編輯和編輯歷史
- Tab 補全和編輯歷史
- 默認交互式解釋器的替代品
- 浮點算術:爭議和限制
- 表示性錯誤
- 附錄
- 交互模式
- 安裝和使用 Python
- 命令行與環境
- 命令行
- 環境變量
- 在Unix平臺中使用Python
- 獲取最新版本的Python
- 構建Python
- 與Python相關的路徑和文件
- 雜項
- 編輯器和集成開發環境
- 在Windows上使用 Python
- 完整安裝程序
- Microsoft Store包
- nuget.org 安裝包
- 可嵌入的包
- 替代捆綁包
- 配置Python
- 適用于Windows的Python啟動器
- 查找模塊
- 附加模塊
- 在Windows上編譯Python
- 其他平臺
- 在蘋果系統上使用 Python
- 獲取和安裝 MacPython
- IDE
- 安裝額外的 Python 包
- Mac 上的圖形界面編程
- 在 Mac 上分發 Python 應用程序
- 其他資源
- Python 語言參考
- 概述
- 其他實現
- 標注
- 詞法分析
- 行結構
- 其他形符
- 標識符和關鍵字
- 字面值
- 運算符
- 分隔符
- 數據模型
- 對象、值與類型
- 標準類型層級結構
- 特殊方法名稱
- 協程
- 執行模型
- 程序的結構
- 命名與綁定
- 異常
- 導入系統
- importlib
- 包
- 搜索
- 加載
- 基于路徑的查找器
- 替換標準導入系統
- Package Relative Imports
- 有關 main 的特殊事項
- 開放問題項
- 參考文獻
- 表達式
- 算術轉換
- 原子
- 原型
- await 表達式
- 冪運算符
- 一元算術和位運算
- 二元算術運算符
- 移位運算
- 二元位運算
- 比較運算
- 布爾運算
- 條件表達式
- lambda 表達式
- 表達式列表
- 求值順序
- 運算符優先級
- 簡單語句
- 表達式語句
- 賦值語句
- assert 語句
- pass 語句
- del 語句
- return 語句
- yield 語句
- raise 語句
- break 語句
- continue 語句
- import 語句
- global 語句
- nonlocal 語句
- 復合語句
- if 語句
- while 語句
- for 語句
- try 語句
- with 語句
- 函數定義
- 類定義
- 協程
- 最高層級組件
- 完整的 Python 程序
- 文件輸入
- 交互式輸入
- 表達式輸入
- 完整的語法規范
- Python 標準庫
- 概述
- 可用性注釋
- 內置函數
- 內置常量
- 由 site 模塊添加的常量
- 內置類型
- 邏輯值檢測
- 布爾運算 — and, or, not
- 比較
- 數字類型 — int, float, complex
- 迭代器類型
- 序列類型 — list, tuple, range
- 文本序列類型 — str
- 二進制序列類型 — bytes, bytearray, memoryview
- 集合類型 — set, frozenset
- 映射類型 — dict
- 上下文管理器類型
- 其他內置類型
- 特殊屬性
- 內置異常
- 基類
- 具體異常
- 警告
- 異常層次結構
- 文本處理服務
- string — 常見的字符串操作
- re — 正則表達式操作
- 模塊 difflib 是一個計算差異的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 數據庫
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函數
- 二進制數據服務
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 數據類型
- datetime — 基礎日期/時間數據類型
- calendar — General calendar-related functions
- collections — 容器數據類型
- collections.abc — 容器的抽象基類
- heapq — 堆隊列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 淺層 (shallow) 和深層 (deep) 復制操作
- pprint — 數據美化輸出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 數字和數學模塊
- numbers — 數字的抽象基類
- math — 數學函數
- cmath — Mathematical functions for complex numbers
- decimal — 十進制定點和浮點運算
- fractions — 分數
- random — 生成偽隨機數
- statistics — Mathematical statistics functions
- 函數式編程模塊
- itertools — 為高效循環而創建迭代器的函數
- functools — 高階函數和可調用對象上的操作
- operator — 標準運算符替代函數
- 文件和目錄訪問
- pathlib — 面向對象的文件系統路徑
- os.path — 常見路徑操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路徑操作函數
- 數據持久化
- pickle —— Python 對象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 數據庫 DB-API 2.0 接口模塊
- 數據壓縮和存檔
- zlib — 與 gzip 兼容的壓縮
- gzip — 對 gzip 格式的支持
- bz2 — 對 bzip2 壓縮算法的支持
- lzma — 用 LZMA 算法壓縮
- zipfile — 在 ZIP 歸檔中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件讀寫
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服務
- hashlib — 安全哈希與消息摘要
- hmac — 基于密鑰的消息驗證
- secrets — Generate secure random numbers for managing secrets
- 通用操作系統服務
- os — 操作系統接口模塊
- io — 處理流的核心工具
- time — 時間的訪問和轉換
- argparse — 命令行選項、參數和子命令解析器
- getopt — C-style parser for command line options
- 模塊 logging — Python 的日志記錄工具
- logging.config — 日志記錄配置
- logging.handlers — Logging handlers
- getpass — 便攜式密碼輸入工具
- curses — 終端字符單元顯示的處理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函數庫
- 并發執行
- threading — 基于線程的并行
- multiprocessing — 基于進程的并行
- concurrent 包
- concurrent.futures — 啟動并行任務
- subprocess — 子進程管理
- sched — 事件調度器
- queue — 一個同步的隊列類
- _thread — 底層多線程 API
- _dummy_thread — _thread 的替代模塊
- dummy_threading — 可直接替代 threading 模塊。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 網絡和進程間通信
- asyncio — 異步 I/O
- socket — 底層網絡接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高級 I/O 復用庫
- asyncore — 異步socket處理器
- asynchat — 異步 socket 指令/響應 處理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互聯網數據處理
- email — 電子郵件與 MIME 處理包
- json — JSON 編碼和解碼器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 數據編碼
- binhex — 對binhex4文件進行編碼和解碼
- binascii — 二進制和 ASCII 碼互轉
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 結構化標記處理工具
- html — 超文本標記語言支持
- html.parser — 簡單的 HTML 和 XHTML 解析器
- html.entities — HTML 一般實體的定義
- XML處理模塊
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互聯網協議和支持
- webbrowser — 方便的Web瀏覽器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 處理模塊
- urllib.request — 用于打開 URL 的可擴展庫
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模塊
- http.client — HTTP協議客戶端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP協議客戶端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服務器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服務端與客戶端模塊
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒體服務
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 讀寫 Sun AU 文件
- wave — 讀寫WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推測圖像類型
- sndhdr — 推測聲音文件的類型
- ossaudiodev — Access to OSS-compatible audio devices
- 國際化
- gettext — 多語種國際化服務
- locale — 國際化服務
- 程序框架
- turtle — 海龜繪圖
- cmd — 支持面向行的命令解釋器
- shlex — Simple lexical analysis
- Tk圖形用戶界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滾動文字控件
- IDLE
- 其他圖形用戶界面(GUI)包
- 開發工具
- typing — 類型標注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 單元測試框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自動將 Python 2 代碼轉為 Python 3 代碼
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 調試和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 測量小代碼片段的執行時間
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 軟件打包和分發
- distutils — 構建和安裝 Python 模塊
- ensurepip — Bootstrapping the pip installer
- venv — 創建虛擬環境
- zipapp — Manage executable Python zip archives
- Python運行時服務
- sys — 系統相關的參數和函數
- sysconfig — Provide access to Python's configuration information
- builtins — 內建對象
- main — 頂層腳本環境
- warnings — Warning control
- dataclasses — 數據類
- contextlib — Utilities for with-statement contexts
- abc — 抽象基類
- atexit — 退出處理器
- traceback — Print or retrieve a stack traceback
- future — Future 語句定義
- gc — 垃圾回收器接口
- inspect — 檢查對象
- site — Site-specific configuration hook
- 自定義 Python 解釋器
- code — Interpreter base classes
- codeop — Compile Python code
- 導入模塊
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找腳本使用的模塊
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 語言服務
- parser — Access Python parse trees
- ast — 抽象語法樹
- symtable — Access to the compiler's symbol tables
- symbol — 與 Python 解析樹一起使用的常量
- token — 與Python解析樹一起使用的常量
- keyword — 檢驗Python關鍵字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊縮進檢測
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字節碼反匯編器
- pickletools — Tools for pickle developers
- 雜項服務
- formatter — Generic output formatting
- Windows系統相關模塊
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注冊表訪問
- winsound — Sound-playing interface for Windows
- Unix 專有服務
- posix — The most common POSIX system calls
- pwd — 用戶密碼數據庫
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 終端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 庫例程
- 被取代的模塊
- optparse — Parser for command line options
- imp — Access the import internals
- 未創建文檔的模塊
- 平臺特定模塊
- 擴展和嵌入 Python 解釋器
- 推薦的第三方工具
- 不使用第三方工具創建擴展
- 使用 C 或 C++ 擴展 Python
- 自定義擴展類型:教程
- 定義擴展類型:已分類主題
- 構建C/C++擴展
- 在Windows平臺編譯C和C++擴展
- 在更大的應用程序中嵌入 CPython 運行時
- Embedding Python in Another Application
- Python/C API 參考手冊
- 概述
- 代碼標準
- 包含文件
- 有用的宏
- 對象、類型和引用計數
- 異常
- 嵌入Python
- 調試構建
- 穩定的應用程序二進制接口
- The Very High Level Layer
- Reference Counting
- 異常處理
- Printing and clearing
- 拋出異常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 標準異常
- 標準警告類別
- 工具
- 操作系統實用程序
- 系統功能
- 過程控制
- 導入模塊
- Data marshalling support
- 語句解釋及變量編譯
- 字符串轉換與格式化
- 反射
- 編解碼器注冊與支持功能
- 抽象對象層
- Object Protocol
- 數字協議
- Sequence Protocol
- Mapping Protocol
- 迭代器協議
- 緩沖協議
- Old Buffer Protocol
- 具體的對象層
- 基本對象
- 數值對象
- 序列對象
- 容器對象
- 函數對象
- 其他對象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置變量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 內存管理
- 概述
- 原始內存接口
- Memory Interface
- 對象分配器
- 默認內存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 對象實現支持
- 在堆中分配對象
- Common Object Structures
- Type 對象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使對象類型支持循環垃圾回收
- API 和 ABI 版本管理
- 分發 Python 模塊
- 關鍵術語
- 開源許可與協作
- 安裝工具
- 閱讀指南
- 我該如何...?
- ...為我的項目選擇一個名字?
- ...創建和分發二進制擴展?
- 安裝 Python 模塊
- 關鍵術語
- 基本使用
- 我應如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安裝 pip ?
- ... 只為當前用戶安裝軟件包?
- ... 安裝科學計算類 Python 軟件包?
- ... 使用并行安裝的多個 Python 版本?
- 常見的安裝問題
- 在 Linux 的系統 Python 版本上安裝
- 未安裝 pip
- 安裝二進制編譯擴展
- Python 常用指引
- 將 Python 2 代碼遷移到 Python 3
- 簡要說明
- 詳情
- 將擴展模塊移植到 Python 3
- 條件編譯
- 對象API的更改
- 模塊初始化和狀態
- CObject 替換為 Capsule
- 其他選項
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 實現描述器
- 摘要
- 定義和簡介
- 描述器協議
- 發起調用描述符
- 描述符示例
- Properties
- 函數和方法
- Static Methods and Class Methods
- 函數式編程指引
- 概述
- 迭代器
- 生成器表達式和列表推導式
- 生成器
- 內置函數
- itertools 模塊
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文獻
- 日志 HOWTO
- 日志基礎教程
- 進階日志教程
- 日志級別
- 有用的處理程序
- 記錄日志中引發的異常
- 使用任意對象作為消息
- 優化
- 日志操作手冊
- 在多個模塊中使用日志
- 在多線程中使用日志
- 使用多個日志處理器和多種格式化
- 在多個地方記錄日志
- 日志服務器配置示例
- 處理日志處理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正則表達式HOWTO
- 概述
- 簡單模式
- 使用正則表達式
- 更多模式能力
- 修改字符串
- 常見問題
- 反饋
- 套接字編程指南
- 套接字
- 創建套接字
- 使用一個套接字
- 斷開連接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 關鍵函數
- Operator 模塊函數
- 升序和降序
- 排序穩定性和排序復雜度
- 使用裝飾-排序-去裝飾的舊方法
- 使用 cmp 參數的舊方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包獲取網絡資源
- 概述
- Fetching URLs
- 處理異常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 腳注
- Argparse 教程
- 概念
- 基礎
- 位置參數介紹
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模塊介紹
- 創建 Address/Network/Interface 對象
- 審查 Address/Network/Interface 對象
- Network 作為 Address 列表
- 比較
- 將IP地址與其他模塊一起使用
- 實例創建失敗時獲取更多詳細信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 檢測CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常見問題
- Python常見問題
- 一般信息
- 現實世界中的 Python
- 編程常見問題
- 一般問題
- 核心語言
- 數字和字符串
- 性能
- 序列(元組/列表)
- 對象
- 模塊
- 設計和歷史常見問題
- 為什么Python使用縮進來分組語句?
- 為什么簡單的算術運算得到奇怪的結果?
- 為什么浮點計算不準確?
- 為什么Python字符串是不可變的?
- 為什么必須在方法定義和調用中顯式使用“self”?
- 為什么不能在表達式中賦值?
- 為什么Python對某些功能(例如list.index())使用方法來實現,而其他功能(例如len(List))使用函數實現?
- 為什么 join()是一個字符串方法而不是列表或元組方法?
- 異常有多快?
- 為什么Python中沒有switch或case語句?
- 難道不能在解釋器中模擬線程,而非得依賴特定于操作系統的線程實現嗎?
- 為什么lambda表達式不能包含語句?
- 可以將Python編譯為機器代碼,C或其他語言嗎?
- Python如何管理內存?
- 為什么CPython不使用更傳統的垃圾回收方案?
- CPython退出時為什么不釋放所有內存?
- 為什么有單獨的元組和列表數據類型?
- 列表是如何在CPython中實現的?
- 字典是如何在CPython中實現的?
- 為什么字典key必須是不可變的?
- 為什么 list.sort() 沒有返回排序列表?
- 如何在Python中指定和實施接口規范?
- 為什么沒有goto?
- 為什么原始字符串(r-strings)不能以反斜杠結尾?
- 為什么Python沒有屬性賦值的“with”語句?
- 為什么 if/while/def/class語句需要冒號?
- 為什么Python在列表和元組的末尾允許使用逗號?
- 代碼庫和插件 FAQ
- 通用的代碼庫問題
- 通用任務
- 線程相關
- 輸入輸出
- 網絡 / Internet 編程
- 數據庫
- 數學和數字
- 擴展/嵌入常見問題
- 可以使用C語言中創建自己的函數嗎?
- 可以使用C++語言中創建自己的函數嗎?
- C很難寫,有沒有其他選擇?
- 如何從C執行任意Python語句?
- 如何從C中評估任意Python表達式?
- 如何從Python對象中提取C的值?
- 如何使用Py_BuildValue()創建任意長度的元組?
- 如何從C調用對象的方法?
- 如何捕獲PyErr_Print()(或打印到stdout / stderr的任何內容)的輸出?
- 如何從C訪問用Python編寫的模塊?
- 如何從Python接口到C ++對象?
- 我使用Setup文件添加了一個模塊,為什么make失敗了?
- 如何調試擴展?
- 我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?
- 如何區分“輸入不完整”和“輸入無效”?
- 如何找到未定義的g++符號__builtin_new或__pure_virtual?
- 能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?
- Python在Windows上的常見問題
- 我怎樣在Windows下運行一個Python程序?
- 我怎么讓 Python 腳本可執行?
- 為什么有時候 Python 程序會啟動緩慢?
- 我怎樣使用Python腳本制作可執行文件?
- *.pyd 文件和DLL文件相同嗎?
- 我怎樣將Python嵌入一個Windows程序?
- 如何讓編輯器不要在我的 Python 源代碼中插入 tab ?
- 如何在不阻塞的情況下檢查按鍵?
- 圖形用戶界面(GUI)常見問題
- 圖形界面常見問題
- Python 是否有平臺無關的圖形界面工具包?
- 有哪些Python的GUI工具是某個平臺專用的?
- 有關Tkinter的問題
- “為什么我的電腦上安裝了 Python ?”
- 什么是Python?
- 為什么我的電腦上安裝了 Python ?
- 我能刪除 Python 嗎?
- 術語對照表
- 文檔說明
- Python 文檔貢獻者
- 解決 Bug
- 文檔錯誤
- 使用 Python 的錯誤追蹤系統
- 開始為 Python 貢獻您的知識
- 版權
- 歷史和許可證
- 軟件歷史
- 訪問Python或以其他方式使用Python的條款和條件
- Python 3.7.3 的 PSF 許可協議
- Python 2.0 的 BeOpen.com 許可協議
- Python 1.6.1 的 CNRI 許可協議
- Python 0.9.0 至 1.2 的 CWI 許可協議
- 集成軟件的許可和認可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec