### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](io.xhtml "io --- 處理流的核心工具") |
- [上一頁](allos.xhtml "通用操作系統服務") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 標準庫](index.xhtml) ?
- [通用操作系統服務](allos.xhtml) ?
- $('.inline-search').show(0); |
# [`os`](#module-os "os: Miscellaneous operating system interfaces.") --- 操作系統接口模塊
**源代碼:** [Lib/os.py](https://github.com/python/cpython/tree/3.7/Lib/os.py) \[https://github.com/python/cpython/tree/3.7/Lib/os.py\]
- - - - - -
該模塊提供了一些方便使用操作系統相關功能的函數。 如果你是想讀寫一個文件,請參閱 [`open()`](functions.xhtml#open "open"),如果你想操作路徑,請參閱 [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.") 模塊,如果你想在命令行上讀取所有文件中的所有行請參閱 [`fileinput`](fileinput.xhtml#module-fileinput "fileinput: Loop over standard input or a list of files.") 模塊。 有關創建臨時文件和目錄的方法,請參閱 [`tempfile`](tempfile.xhtml#module-tempfile "tempfile: Generate temporary files and directories.") 模塊,對于高級文件目錄處理,請參閱 [`shutil`](shutil.xhtml#module-shutil "shutil: High-level file operations, including copying.") 模塊。
關于這些函數的可用性的說明:
- 所有 Python 內建的操作系統相關的模塊的設計都是為了使得在同一功能可用的情況下,保持接口的一致性;例如,函數 `os.stat(path)` 以相同的格式返回關于 *path* 的統計信息(這個函數同時也是起源于 POSIX 接口)。
- 針對特定的操作的拓展同樣在可用于 [`os`](#module-os "os: Miscellaneous operating system interfaces.") 模塊,但是使用它們必然會對可移植性產生威脅。
- 所有接受路徑或文件名的函數都同時支持字節串和字符串對象,并在返回路徑或文件名時使用相應類型的對象作為結果。
注解
此模塊的所有函數在遇到不可用或不可訪問的文件名或路徑,以及其他類型正確,但不被操作系統接受的參數時,會引發 [`OSError`](exceptions.xhtml#OSError "OSError") 異常。
*exception* `os.``error`內建的 [`OSError`](exceptions.xhtml#OSError "OSError") 異常的一個別名。
`os.``name`導入的依賴特定操作系統的模塊的名稱。以下名稱目前已注冊: `'posix'`, `'nt'`, `'java'`.
參見
[`sys.platform`](sys.xhtml#sys.platform "sys.platform") 有更詳細的描述. [`os.uname()`](#os.uname "os.uname") 只給出系統提供的版本信息。
[`platform`](platform.xhtml#module-platform "platform: Retrieves as much platform identifying data as possible.") 模塊對系統的標識有更詳細的檢查。
## 文件名,命令行參數,以及環境變量。
在 Python 中,使用字符串類型表示文件名、命令行參數和環境變量。 在某些系統上,在將這些字符串傳遞給操作系統之前,必須將這些字符串解碼為字節。 Python 使用文件系統編碼來執行此轉換(請參閱 [`sys.getfilesystemencoding()`](sys.xhtml#sys.getfilesystemencoding "sys.getfilesystemencoding") )。
在 3.1 版更改: 在某些系統上,使用文件系統編碼進行轉換可能會失敗。 在這種情況下,Python 會使用 [代理轉義編碼錯誤處理器](codecs.xhtml#surrogateescape),這意味著在解碼時,不可解碼的字節被 Unicode 字符 U+DCxx 替換,并且這些字節在編碼時再次轉換為原始字節。
文件系統編碼必須保證成功解碼小于 128 的所有字節。如果文件系統編碼無法提供此保證, API 函數可能會引發 UnicodeErrors 。
## 進程參數
這些函數和數據項提供了操作當前進程和用戶的信息。
`os.``ctermid`()返回與進程控制終端對應的文件名。
[可用性](intro.xhtml#availability): Unix。
`os.``environ`一個表示字符串環境的 [mapping](../glossary.xhtml#term-mapping) 對象。 例如,`environ['HOME']` 是你的主目錄(在某些平臺上)的路徑名,相當于 C 中的 `getenv("HOME")`。
這個映射是在第一次導入 [`os`](#module-os "os: Miscellaneous operating system interfaces.") 模塊時捕獲的,通常作為 Python 啟動時處理 `site.py` 的一部分。除了通過直接修改 `os.environ` 之外,在此之后對環境所做的更改不會反映在 `os.environ` 中。
如果平臺支持 [`putenv()`](#os.putenv "os.putenv") 函數,這個映射除了可以用于查詢環境外還能用于修改環境。 當這個映射被修改時,[`putenv()`](#os.putenv "os.putenv") 將被自動調用。
在Unix系統上,鍵和值會使用 [`sys.getfilesystemencoding()`](sys.xhtml#sys.getfilesystemencoding "sys.getfilesystemencoding") 和 `'surrogateescape'` 的錯誤處理。如果你想使用其他的編碼,使用 [`environb`](#os.environb "os.environb")。
注解
直接調用 [`putenv()`](#os.putenv "os.putenv") 并不會影響 `os.environ`,所以推薦直接修改``os.environ``。
注解
在某些平臺上,包括 FreeBSD 和 Mac OS X,設置 `environ` 可能導致內存泄露。參閱 `putenv()` 的系統文檔。
如果平臺沒有提供 [`putenv()`](#os.putenv "os.putenv"), 為了使啟動的子進程使用修改后的環境,一份修改后的映射會被傳給合適的進程創建函數。
如果平臺支持 [`unsetenv()`](#os.unsetenv "os.unsetenv") 函數,你可以通過刪除映射中元素的方式來刪除對應的環境變量。當一個元素被從 `os.environ` 刪除時,以及 `pop()` 或 `clear()` 被調用時, [`unsetenv()`](#os.unsetenv "os.unsetenv") 會被自動調用。
`os.``environb`字節版本的 [`environ`](#os.environ "os.environ"): 一個以字節串表示環境的 [mapping](../glossary.xhtml#term-mapping) 對象。 [`environ`](#os.environ "os.environ") 和 [`environb`](#os.environb "os.environb") 是同步的(修改 [`environb`](#os.environb "os.environb") 會更新 [`environ`](#os.environ "os.environ"),反之亦然)。
只有在 [`supports_bytes_environ`](#os.supports_bytes_environ "os.supports_bytes_environ") 為 True 的時候 [`environb`](#os.environb "os.environb") 才是可用的。
3\.2 新版功能.
`os.``chdir`(*path*)`os.``fchdir`(*fd*)`os.``getcwd`()以上函數請參閱 [Files and Directories](#os-file-dir) 。
`os.``fsencode`(*filename*)編碼 [路徑類](../glossary.xhtml#term-path-like-object) *文件名* 為文件系統接受的形式,使用 `'surrogateescape'` 代理轉義編碼錯誤處理器,在Windows系統上會使用 `'strict'` ;返回 [`bytes`](stdtypes.xhtml#bytes "bytes") 字節類型不變。
[`fsdecode()`](#os.fsdecode "os.fsdecode") 是此函數的逆向函數。
3\.2 新版功能.
在 3.6 版更改: 增加對實現了 [`os.PathLike`](#os.PathLike "os.PathLike") 接口的對象的支持。
`os.``fsdecode`(*filename*)從文件系統編碼方式解碼為 [路徑類](../glossary.xhtml#term-path-like-object) 文件名,使用 `'surrogateescape'` 代理轉義編碼錯誤處理器,在Windows系統上會使用 `'strict'` ;返回 [`str`](stdtypes.xhtml#str "str") 字符串不變。
[`fsencode()`](#os.fsencode "os.fsencode") 是此函數的逆向函數。
3\.2 新版功能.
在 3.6 版更改: 增加對實現了 [`os.PathLike`](#os.PathLike "os.PathLike") 接口的對象的支持。
`os.``fspath`(*path*)返回路徑的文件系統表示。
如果傳入的是 [`str`](stdtypes.xhtml#str "str") 或 [`bytes`](stdtypes.xhtml#bytes "bytes") 類型的字符串,將原樣返回。否則 [`__fspath__()`](#os.PathLike.__fspath__ "os.PathLike.__fspath__") 將被調用,如果得到的是一個 [`str`](stdtypes.xhtml#str "str") 或 [`bytes`](stdtypes.xhtml#bytes "bytes") 類型的對象,那就返回這個值。其他所有情況則會拋出 [`TypeError`](exceptions.xhtml#TypeError "TypeError") 異常。
3\.6 新版功能.
*class* `os.``PathLike`描述表示一個文件系統路徑的 [abstract base class](../glossary.xhtml#term-abstract-base-class) ,如 [`pathlib.PurePath`](pathlib.xhtml#pathlib.PurePath "pathlib.PurePath") 。
3\.6 新版功能.
*abstractmethod* `__fspath__`()返回當前對象的文件系統表示。
這個方法只應該返回一個 [`str`](stdtypes.xhtml#str "str") 字符串或 [`bytes`](stdtypes.xhtml#bytes "bytes") 字節串,請優先選擇 [`str`](stdtypes.xhtml#str "str") 字符串。
`os.``getenv`(*key*, *default=None*)如果存在,返回環境變量 *key* 的值,否則返回 *default*。 *key* , *default* 和返回值均為 str 字符串類型。
在Unix系統上,鍵和值會使用 [`sys.getfilesystemencoding()`](sys.xhtml#sys.getfilesystemencoding "sys.getfilesystemencoding") 和``'surrogateescape'`` 錯誤處理進行解碼。如果你想使用其他的編碼,使用 [`os.getenvb()`](#os.getenvb "os.getenvb")。
[可用性](intro.xhtml#availability): 大部分的Unix系統,Windows。
`os.``getenvb`(*key*, *default=None*)如果存在環境變量 *key* 那么返回其值,否則返回 *default*。 *key* , *default* 和返回值均為bytes字節串類型。
[`getenvb()`](#os.getenvb "os.getenvb") 僅在 [`supports_bytes_environ`](#os.supports_bytes_environ "os.supports_bytes_environ") 為 True 時可用
[可用性](intro.xhtml#availability): 大部分的Unix系統。
3\.2 新版功能.
`os.``get_exec_path`(*env=None*)返回將用于搜索可執行文件的目錄列表,與在外殼程序中啟動一個進程時相似。指定的 *env* 應為用于搜索 PATH 的環境變量字典。默認情況下,當 *env* 為 `None` 時,將會使用 [`environ`](#os.environ "os.environ") 。
3\.2 新版功能.
`os.``getegid`()返回當前進程的有效組ID。對應當前進程執行文件的 "set id" 位。
[可用性](intro.xhtml#availability): Unix。
`os.``geteuid`()返回當前進程的有效用戶ID。
[可用性](intro.xhtml#availability): Unix。
`os.``getgid`()返回當前進程的實際組ID。
[可用性](intro.xhtml#availability): Unix。
`os.``getgrouplist`(*user*, *group*)返回該用戶所在的組 ID 列表。可能 *group* 參數沒有在返回的列表中,實際上用戶應該也是屬于該 *group*。*group* 參數一般可以從儲存賬戶信息的密碼記錄文件中找到。
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``getgroups`()返回當前進程對應的組ID列表
[可用性](intro.xhtml#availability): Unix。
注解
在Mac OS X系統中,[`getgroups()`](#os.getgroups "os.getgroups") 會和其他 Unix 平臺有些不同。如果 Python 解釋器是在 `10.5` 或更早版本中部署,[`getgroups()`](#os.getgroups "os.getgroups") 返回當前用戶進程相關的有效組ID列表。 該列表長度由于系統預設的接口限制,最長為 16。 而且在適當的權限下,返回結果還會因 [`getgroups()`](#os.getgroups "os.getgroups") 而發生變化;如果 Python 解釋器是在 `10.5` 以上版本中部署,[`getgroups()`](#os.getgroups "os.getgroups") 返回進程所屬有效用戶 ID 所對應的用戶的組 ID 列表,組用戶列表可能因為進程的生存周期而發生變動,而且也不會因為 [`setgroups()`](#os.setgroups "os.setgroups") 的調用而發生,返回的組用戶列表長度也沒有長度 16 的限制。在部署中,Python 解釋器用到的變量 `MACOSX_DEPLOYMENT_TARGET` 可以用 [`sysconfig.get_config_var()`](sysconfig.xhtml#sysconfig.get_config_var "sysconfig.get_config_var")。
`os.``getlogin`()返回通過控制終端進程進行登錄的用戶名。在多數情況下,使用 [`getpass.getuser()`](getpass.xhtml#getpass.getuser "getpass.getuser") 會更有效,因為后者會通過檢查環境變量 `LOGNAME` 或 `USERNAME` 來查找用戶,再由 `pwd.getpwuid(os.getuid())[0]` 來獲取當前用戶 ID 的登錄名。
[可用性](intro.xhtml#availability): Unix, Windows。
`os.``getpgid`(*pid*)根據進程id *pid* 返回進程的組 ID 列表。如果 *pid* 為 0,則返回當前進程的進程組 ID 列表
[可用性](intro.xhtml#availability): Unix。
`os.``getpgrp`()返回當時進程組的ID
[可用性](intro.xhtml#availability): Unix。
`os.``getpid`()返回當前進程ID
`os.``getppid`()返回父進程ID。當父進程已經結束,在Unix中返回的ID是初始進程(1)中的一個,在Windows中仍然是同一個進程ID,該進程ID有可能已經被進行進程所占用。
[可用性](intro.xhtml#availability): Unix, Windows。
在 3.2 版更改: 添加WIndows的支持。
`os.``getpriority`(*which*, *who*)獲取程序調度優先級。*which* 參數值可以是 [`PRIO_PROCESS`](#os.PRIO_PROCESS "os.PRIO_PROCESS"),[`PRIO_PGRP`](#os.PRIO_PGRP "os.PRIO_PGRP"),或 [`PRIO_USER`](#os.PRIO_USER "os.PRIO_USER") 中的一個,*who* 是相對于 *which* ([`PRIO_PROCESS`](#os.PRIO_PROCESS "os.PRIO_PROCESS") 的進程標識符,[`PRIO_PGRP`](#os.PRIO_PGRP "os.PRIO_PGRP") 的進程組標識符和 [`PRIO_USER`](#os.PRIO_USER "os.PRIO_USER") 的用戶ID)。當 *who* 為 0 時(分別)表示調用的進程,調用進程的進程組或調用進程所屬的真實用戶 ID。
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``PRIO_PROCESS``os.``PRIO_PGRP``os.``PRIO_USER`函數 [`getpriority()`](#os.getpriority "os.getpriority") 和 [`setpriority()`](#os.setpriority "os.setpriority") 的參數。
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``getresuid`()返回一個由 (ruid, euid, suid) 所組成的元組,分別表示當前進程的真實用戶ID,有效用戶ID和甲暫存用戶ID。
[可用性](intro.xhtml#availability): Unix。
3\.2 新版功能.
`os.``getresgid`()返回一個由 (rgid, egid, sgid) 所組成的元組,分別表示當前進程的真實組ID,有效組ID和暫存組ID。
[可用性](intro.xhtml#availability): Unix。
3\.2 新版功能.
`os.``getuid`()返回當前進程的真實用戶ID。
[可用性](intro.xhtml#availability): Unix。
`os.``initgroups`(*username*, *gid*)調用系統 initgroups(),使用指定用戶所在的所有值來初始化組訪問列表,包括指定的組ID。
[可用性](intro.xhtml#availability): Unix。
3\.2 新版功能.
`os.``putenv`(*key*, *value*)將名為 *key* 的環境變量值設置為 *value*。該變量名修改會影響由 [`os.system()`](#os.system "os.system"), [`popen()`](#os.popen "os.popen") ,[`fork()`](#os.fork "os.fork") 和 [`execv()`](#os.execv "os.execv") 發起的子進程。
[可用性](intro.xhtml#availability): 大部分的Unix系統,Windows。
注解
在一些平臺,包括 FreeBSD 和 Mac OS X,設置 `environ` 可能導致內存泄露。詳情參考 putenv 相關系統文檔。
當系統支持 [`putenv()`](#os.putenv "os.putenv") 時,`os.environ` 中的參數賦值會自動轉換為對 [`putenv()`](#os.putenv "os.putenv") 的調用。不過 [`putenv()`](#os.putenv "os.putenv") 的調用不會更新 `os.environ`,因此最好使用 `os.environ` 對變量賦值。
`os.``setegid`(*egid*)設置當前進程的有效組ID。
[可用性](intro.xhtml#availability): Unix。
`os.``seteuid`(*euid*)設置當前進程的有效用戶ID。
[可用性](intro.xhtml#availability): Unix。
`os.``setgid`(*gid*)設置當前進程的組ID。
[可用性](intro.xhtml#availability): Unix。
`os.``setgroups`(*groups*)將 *group* 參數值設置為與當進程相關聯的附加組ID列表。*group* 參數必須為一個序列,每個元素應為每個組的數字ID。該操作通常只適用于超級用戶。
[可用性](intro.xhtml#availability): Unix。
注解
在 Mac OS X 中,*groups* 的長度不能超過系統定義的最大有效組 ID 個數,一般為 16。 如果它沒有返回與調用 setgroups() 所設置的相同的組列表,請參閱 [`getgroups()`](#os.getgroups "os.getgroups") 的文檔。
`os.``setpgrp`()根據已實現的版本(如果有)來調用系統 `setpgrp()` 或 `setpgrp(0, 0)` 。相關說明,請參考 Unix 手冊。
[可用性](intro.xhtml#availability): Unix。
`os.``setpgid`(*pid*, *pgrp*)使用系統調用 `setpgid()`,將 *pid* 對應進程的組ID設置為 *pgrp*。相關說明,請參考 Unix 手冊。
[可用性](intro.xhtml#availability): Unix。
`os.``setpriority`(*which*, *who*, *priority*)設置程序調度優先級。 *which* 的值為 [`PRIO_PROCESS`](#os.PRIO_PROCESS "os.PRIO_PROCESS"), [`PRIO_PGRP`](#os.PRIO_PGRP "os.PRIO_PGRP") 或 [`PRIO_USER`](#os.PRIO_USER "os.PRIO_USER") 之一,而 *who* 會相對于 *which* ([`PRIO_PROCESS`](#os.PRIO_PROCESS "os.PRIO_PROCESS") 的進程標識符, [`PRIO_PGRP`](#os.PRIO_PGRP "os.PRIO_PGRP") 的進程組標識符和 [`PRIO_USER`](#os.PRIO_USER "os.PRIO_USER") 的用戶 ID) 被解析。 *who* 值為零 (分別) 表示調用進程,調用進程的進程組或調用進程的真實用戶 ID。 *priority* 是范圍在 -20 至 19 的值。 默認優先級為 0;較小的優先級數值會更優先被調度。
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``setregid`(*rgid*, *egid*)設置當前進程的真實和有效組ID。
[可用性](intro.xhtml#availability): Unix。
`os.``setresgid`(*rgid*, *egid*, *sgid*)設置當前進程的真實,有效和暫存組ID。
[可用性](intro.xhtml#availability): Unix。
3\.2 新版功能.
`os.``setresuid`(*ruid*, *euid*, *suid*)設置當前進程的真實,有效和暫存用戶ID。
[可用性](intro.xhtml#availability): Unix。
3\.2 新版功能.
`os.``setreuid`(*ruid*, *euid*)設置當前進程的真實和有效用戶ID。
[可用性](intro.xhtml#availability): Unix。
`os.``getsid`(*pid*)調用系統調用 `getsid()`。 相關語義請參閱 Unix 手冊。
[可用性](intro.xhtml#availability): Unix。
`os.``setsid`()使用系統調用 `getsid()`。相關說明,請參考 Unix 手冊。
[可用性](intro.xhtml#availability): Unix。
`os.``setuid`(*uid*)設置當前進程的用戶ID。
[可用性](intro.xhtml#availability): Unix。
`os.``strerror`(*code*)根據 *code* 中的錯誤碼返回錯誤消息。 在某些平臺上當給出未知錯誤碼時 `strerror()` 將返回 `NULL` 并會引發 [`ValueError`](exceptions.xhtml#ValueError "ValueError")。
`os.``supports_bytes_environ`如果操作系統上原生環境類型是字節型則為 `True` (例如在 Windows 上為 `False`)。
3\.2 新版功能.
`os.``umask`(*mask*)設定當前數值掩碼并返回之前的掩碼。
`os.``uname`()返回當前操作系統的識別信息。返回值是一個有5個屬性的對象:
- `sysname` - 操作系統名
- `nodename` - 機器在網絡上的名稱(需要先設定)
- `release` - 操作系統發行信息
- `version` - 操作系統版本信息
- `machine` - 硬件標識符
為了向后兼容,該對象也是可迭代的,像是一個按照 `sysname`,`nodename`,`release`,`version`,和 `machine` 順序組成的元組。
有些系統會將 `nodename` 截短為 8 個字符或截短至前綴部分;獲取主機名的一個更好方式是 [`socket.gethostname()`](socket.xhtml#socket.gethostname "socket.gethostname") 或甚至可以用 `socket.gethostbyaddr(socket.gethostname())`。
[可用性](intro.xhtml#availability): 較新的 Unix 版本。
在 3.3 版更改: 返回結果的類型由元組變成一個類似元組的對象,同時具有命名的屬性。
`os.``unsetenv`(*key*)取消設置(刪除)名為 *key* 的環境變量。變量名的改變會影響由 [`os.system()`](#os.system "os.system"),[`popen()`](#os.popen "os.popen"),[`fork()`](#os.fork "os.fork") 和 [`execv()`](#os.execv "os.execv") 觸發的子進程。
當系統支持 [`unsetenv()`](#os.unsetenv "os.unsetenv") ,刪除在 `os.environ` 中的變量會自動轉換為對 [`unsetenv()`](#os.unsetenv "os.unsetenv") 的調用。但是 [`unsetenv()`](#os.unsetenv "os.unsetenv") 不能更新 `os.environ`,因此最好直接刪除 `os.environ` 中的變量。
[可用性](intro.xhtml#availability): 大部分的Unix系統,Windows。
## 創建文件對象
該函數創建新的 [文件對象](../glossary.xhtml#term-file-object)。 (另見 [`open()`](#os.open "os.open") 關于打開文件的說明。)
`os.``fdopen`(*fd*, *\*args*, *\*\*kwargs*)返回打開文件描述符 *fd* 對應文件的對象。類似內建 [`open()`](functions.xhtml#open "open") 函數,二者接受同樣的參數。不同之處在于 [`fdopen()`](#os.fdopen "os.fdopen") 第一個參數應該為整數。
## 文件描述符操作
這些函數對文件描述符所引用的 I/O 流進行操作。
文件描述符是一些小的整數,對應于當前進程所打開的文件。例如,標準輸入的文件描述符通常是0,標準輸出是1,標準錯誤是2。之后被進程打開的文件的文件描述符會被依次指定為3,4,5等。“文件描述符”這個詞有點誤導性,在 Unix 平臺中套接字和管道也被文件描述符所引用。
當需要時,可以用 [`fileno()`](io.xhtml#io.IOBase.fileno "io.IOBase.fileno") 可以獲得 [file object](../glossary.xhtml#term-file-object) 所對應的文件描述符。需要注意的是,直接使用文件描述符會繞過文件對象的方法,會忽略如數據內部緩沖等情況。
`os.``close`(*fd*)關閉文件描述符 *fd*。
注解
該功能適用于低級 I/O 操作,必須用于 [`os.open()`](#os.open "os.open") 或 [`pipe()`](#os.pipe "os.pipe") 返回的文件描述符。關閉由內建函數 [`open()`](functions.xhtml#open "open") , [`popen()`](#os.popen "os.popen") 或 [`fdopen()`](#os.fdopen "os.fdopen") 返回的 "文件對象",則使用其相應的 [`close()`](io.xhtml#io.IOBase.close "io.IOBase.close") 方法。
`os.``closerange`(*fd\_low*, *fd\_high*)關閉從 *fd\_low* (包括)到 *fd\_high* (排除)間的文件描述符,并忽略錯誤。類似(但快于):
```
for fd in range(fd_low, fd_high):
try:
os.close(fd)
except OSError:
pass
```
`os.``device_encoding`(*fd*)如果連接到終端,則返回一個與 *fd* 關聯的設備描述字符,否則返回 [`None`](constants.xhtml#None "None")。
`os.``dup`(*fd*)返回一個文件描述符 *fd* 的副本。該文件描述符的副本是 [不可繼承的](#fd-inheritance)。
在 Windows 中,當復制一個標準流(0: stdin, 1: stdout, 2: stderr)時,新的文件描述符是 [可繼承的](#fd-inheritance)。
在 3.4 版更改: 新的文件描述符現在是不可繼承的。
`os.``dup2`(*fd*, *fd2*, *inheritable=True*)把文件描述符 *fd* 復制為 *fd2*,必要時先關閉后者。返回 *fd2*。新的文件描述符默認是 [可繼承的](#fd-inheritance),除非在 *inheritable* 為 `False` 時,是不可繼承的。
在 3.4 版更改: 添加可選參數 *inheritable*。
在 3.7 版更改: 成功時返回 *fd2*,以過去的版本中,總是返回 `None`。
`os.``fchmod`(*fd*, *mode*)將 *fd* 指定文件的權限狀態修改為 *mode*。可以參考 [`chmod()`](#os.chmod "os.chmod") 中列出 *mode* 的可用值。從Python 3.3開始,這相當于 `os.chmod(fd, mode)`。
[可用性](intro.xhtml#availability): Unix。
`os.``fchown`(*fd*, *uid*, *gid*)分別將 *fd* 指定文件的所有者和組 ID 修改為 *uid* 和 *gid* 的值。若不想變更其中的某個 ID,可將相應值設為 -1。參考 [`chown()`](#os.chown "os.chown")。從 Python 3.3 開始,這相當于 `os.chown(fd, uid, gid)`。
[可用性](intro.xhtml#availability): Unix。
`os.``fdatasync`(*fd*)強制將文件描述符 *fd* 指定文件寫入磁盤。不強制更新元數據。
[可用性](intro.xhtml#availability): Unix。
注解
該功能在 MacOS 中不可用。
`os.``fpathconf`(*fd*, *name*)Return system configuration information relevant to an open file. *name*specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the `pathconf_names` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted.
If *name* is a string and is not known, [`ValueError`](exceptions.xhtml#ValueError "ValueError") is raised. If a specific value for *name* is not supported by the host system, even if it is included in `pathconf_names`, an [`OSError`](exceptions.xhtml#OSError "OSError") is raised with [`errno.EINVAL`](errno.xhtml#errno.EINVAL "errno.EINVAL") for the error number.
從 Python 3.3 起,此功能等價于 `os.pathconf(fd, name)`。
[可用性](intro.xhtml#availability): Unix。
`os.``fstat`(*fd*)獲取文件描述符 *fd* 的狀態. 返回一個 [`stat_result`](#os.stat_result "os.stat_result") 對象。
從 Python 3.3 起,此功能等價于 `os.stat(fd)`。
參見
[`stat()`](#os.stat "os.stat") 函數。
`os.``fstatvfs`(*fd*)Return information about the filesystem containing the file associated with file descriptor *fd*, like [`statvfs()`](#os.statvfs "os.statvfs"). As of Python 3.3, this is equivalent to `os.statvfs(fd)`.
[可用性](intro.xhtml#availability): Unix。
`os.``fsync`(*fd*)Force write of file with filedescriptor *fd* to disk. On Unix, this calls the native `fsync()` function; on Windows, the MS `_commit()` function.
If you're starting with a buffered Python [file object](../glossary.xhtml#term-file-object) *f*, first do `f.flush()`, and then do `os.fsync(f.fileno())`, to ensure that all internal buffers associated with *f* are written to disk.
[可用性](intro.xhtml#availability): Unix, Windows。
`os.``ftruncate`(*fd*, *length*)Truncate the file corresponding to file descriptor *fd*, so that it is at most *length* bytes in size. As of Python 3.3, this is equivalent to `os.truncate(fd, length)`.
[可用性](intro.xhtml#availability): Unix, Windows。
在 3.5 版更改: 添加了 Windows 支持
`os.``get_blocking`(*fd*)Get the blocking mode of the file descriptor: `False` if the [`O_NONBLOCK`](#os.O_NONBLOCK "os.O_NONBLOCK") flag is set, `True` if the flag is cleared.
See also [`set_blocking()`](#os.set_blocking "os.set_blocking") and [`socket.socket.setblocking()`](socket.xhtml#socket.socket.setblocking "socket.socket.setblocking").
[可用性](intro.xhtml#availability): Unix。
3\.5 新版功能.
`os.``isatty`(*fd*)Return `True` if the file descriptor *fd* is open and connected to a tty(-like) device, else `False`.
`os.``lockf`(*fd*, *cmd*, *len*)Apply, test or remove a POSIX lock on an open file descriptor. *fd* is an open file descriptor. *cmd* specifies the command to use - one of [`F_LOCK`](#os.F_LOCK "os.F_LOCK"), [`F_TLOCK`](#os.F_TLOCK "os.F_TLOCK"), [`F_ULOCK`](#os.F_ULOCK "os.F_ULOCK") or [`F_TEST`](#os.F_TEST "os.F_TEST"). *len* specifies the section of the file to lock.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``F_LOCK``os.``F_TLOCK``os.``F_ULOCK``os.``F_TEST`Flags that specify what action [`lockf()`](#os.lockf "os.lockf") will take.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``lseek`(*fd*, *pos*, *how*)Set the current position of file descriptor *fd* to position *pos*, modified by *how*: [`SEEK_SET`](#os.SEEK_SET "os.SEEK_SET") or `0` to set the position relative to the beginning of the file; [`SEEK_CUR`](#os.SEEK_CUR "os.SEEK_CUR") or `1` to set it relative to the current position; [`SEEK_END`](#os.SEEK_END "os.SEEK_END") or `2` to set it relative to the end of the file. Return the new cursor position in bytes, starting from the beginning.
`os.``SEEK_SET``os.``SEEK_CUR``os.``SEEK_END`Parameters to the [`lseek()`](#os.lseek "os.lseek") function. Their values are 0, 1, and 2, respectively.
3\.3 新版功能: Some operating systems could support additional values, like `os.SEEK_HOLE` or `os.SEEK_DATA`.
`os.``open`(*path*, *flags*, *mode=0o777*, *\**, *dir\_fd=None*)Open the file *path* and set various flags according to *flags* and possibly its mode according to *mode*. When computing *mode*, the current umask value is first masked out. Return the file descriptor for the newly opened file. The new file descriptor is [non-inheritable](#fd-inheritance).
For a description of the flag and mode values, see the C run-time documentation; flag constants (like [`O_RDONLY`](#os.O_RDONLY "os.O_RDONLY") and [`O_WRONLY`](#os.O_WRONLY "os.O_WRONLY")) are defined in the [`os`](#module-os "os: Miscellaneous operating system interfaces.") module. In particular, on Windows adding [`O_BINARY`](#os.O_BINARY "os.O_BINARY") is needed to open files in binary mode.
This function can support [paths relative to directory descriptors](#dir-fd) with the *dir\_fd* parameter.
在 3.4 版更改: 新的文件描述符現在是不可繼承的。
注解
This function is intended for low-level I/O. For normal usage, use the built-in function [`open()`](functions.xhtml#open "open"), which returns a [file object](../glossary.xhtml#term-file-object) with `read()` and `write()` methods (and many more). To wrap a file descriptor in a file object, use [`fdopen()`](#os.fdopen "os.fdopen").
3\.3 新版功能: *dir\_fd* 參數。
在 3.5 版更改: 如果系統調用被中斷,但信號處理程序沒有觸發異常,此函數現在會重試系統調用,而不是觸發 [`InterruptedError`](exceptions.xhtml#InterruptedError "InterruptedError") 異常 (原因詳見 [**PEP 475**](https://www.python.org/dev/peps/pep-0475) \[https://www.python.org/dev/peps/pep-0475\])。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
The following constants are options for the *flags* parameter to the [`open()`](#os.open "os.open") function. They can be combined using the bitwise OR operator `|`. Some of them are not available on all platforms. For descriptions of their availability and use, consult the *open(2)* manual page on Unix or [the MSDN](https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx) \[https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx\] on Windows.
`os.``O_RDONLY``os.``O_WRONLY``os.``O_RDWR``os.``O_APPEND``os.``O_CREAT``os.``O_EXCL``os.``O_TRUNC`The above constants are available on Unix and Windows.
`os.``O_DSYNC``os.``O_RSYNC``os.``O_SYNC``os.``O_NDELAY``os.``O_NONBLOCK``os.``O_NOCTTY``os.``O_CLOEXEC`這個常數僅在 Unix 系統中可用。
在 3.3 版更改: Add [`O_CLOEXEC`](#os.O_CLOEXEC "os.O_CLOEXEC") constant.
`os.``O_BINARY``os.``O_NOINHERIT``os.``O_SHORT_LIVED``os.``O_TEMPORARY``os.``O_RANDOM``os.``O_SEQUENTIAL``os.``O_TEXT`這個常數僅在 Windows 系統中可用。
`os.``O_ASYNC``os.``O_DIRECT``os.``O_DIRECTORY``os.``O_NOFOLLOW``os.``O_NOATIME``os.``O_PATH``os.``O_TMPFILE``os.``O_SHLOCK``os.``O_EXLOCK`The above constants are extensions and not present if they are not defined by the C library.
在 3.4 版更改: Add [`O_PATH`](#os.O_PATH "os.O_PATH") on systems that support it. Add [`O_TMPFILE`](#os.O_TMPFILE "os.O_TMPFILE"), only available on Linux Kernel 3.11 or newer.
`os.``openpty`()Open a new pseudo-terminal pair. Return a pair of file descriptors `(master, slave)` for the pty and the tty, respectively. The new file descriptors are [non-inheritable](#fd-inheritance). For a (slightly) more portable approach, use the [`pty`](pty.xhtml#module-pty "pty: Pseudo-Terminal Handling for Linux. (Linux)") module.
[可用性](intro.xhtml#availability): 某些 Unix。
在 3.4 版更改: 新的文件描述符不再可繼承。
`os.``pipe`()Create a pipe. Return a pair of file descriptors `(r, w)` usable for reading and writing, respectively. The new file descriptor is [non-inheritable](#fd-inheritance).
[可用性](intro.xhtml#availability): Unix, Windows。
在 3.4 版更改: 新的文件描述符不再可繼承。
`os.``pipe2`(*flags*)Create a pipe with *flags* set atomically. *flags* can be constructed by ORing together one or more of these values: [`O_NONBLOCK`](#os.O_NONBLOCK "os.O_NONBLOCK"), [`O_CLOEXEC`](#os.O_CLOEXEC "os.O_CLOEXEC"). Return a pair of file descriptors `(r, w)` usable for reading and writing, respectively.
[可用性](intro.xhtml#availability): 某些 Unix。
3\.3 新版功能.
`os.``posix_fallocate`(*fd*, *offset*, *len*)Ensures that enough disk space is allocated for the file specified by *fd*starting from *offset* and continuing for *len* bytes.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``posix_fadvise`(*fd*, *offset*, *len*, *advice*)Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations. The advice applies to the region of the file specified by *fd* starting at *offset* and continuing for *len* bytes. *advice* is one of [`POSIX_FADV_NORMAL`](#os.POSIX_FADV_NORMAL "os.POSIX_FADV_NORMAL"), [`POSIX_FADV_SEQUENTIAL`](#os.POSIX_FADV_SEQUENTIAL "os.POSIX_FADV_SEQUENTIAL"), [`POSIX_FADV_RANDOM`](#os.POSIX_FADV_RANDOM "os.POSIX_FADV_RANDOM"), [`POSIX_FADV_NOREUSE`](#os.POSIX_FADV_NOREUSE "os.POSIX_FADV_NOREUSE"), [`POSIX_FADV_WILLNEED`](#os.POSIX_FADV_WILLNEED "os.POSIX_FADV_WILLNEED") or [`POSIX_FADV_DONTNEED`](#os.POSIX_FADV_DONTNEED "os.POSIX_FADV_DONTNEED").
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``POSIX_FADV_NORMAL``os.``POSIX_FADV_SEQUENTIAL``os.``POSIX_FADV_RANDOM``os.``POSIX_FADV_NOREUSE``os.``POSIX_FADV_WILLNEED``os.``POSIX_FADV_DONTNEED`Flags that can be used in *advice* in [`posix_fadvise()`](#os.posix_fadvise "os.posix_fadvise") that specify the access pattern that is likely to be used.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``pread`(*fd*, *n*, *offset*)Read at most *n* bytes from file descriptor *fd* at a position of *offset*, leaving the file offset unchanged.
Return a bytestring containing the bytes read. If the end of the file referred to by *fd* has been reached, an empty bytes object is returned.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``preadv`(*fd*, *buffers*, *offset*, *flags=0*)Read from a file descriptor *fd* at a position of *offset* into mutable [bytes-like objects](../glossary.xhtml#term-bytes-like-object) *buffers*, leaving the file offset unchanged. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.
The flags argument contains a bitwise OR of zero or more of the following flags:
- [`RWF_HIPRI`](#os.RWF_HIPRI "os.RWF_HIPRI")
- [`RWF_NOWAIT`](#os.RWF_NOWAIT "os.RWF_NOWAIT")
Return the total number of bytes actually read which can be less than the total capacity of all the objects.
The operating system may set a limit ([`sysconf()`](#os.sysconf "os.sysconf") value `'SC_IOV_MAX'`) on the number of buffers that can be used.
Combine the functionality of [`os.readv()`](#os.readv "os.readv") and [`os.pread()`](#os.pread "os.pread").
[Availability](intro.xhtml#availability): Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer. Using flags requires Linux 4.6 or newer.
3\.7 新版功能.
`os.``RWF_NOWAIT`Do not wait for data which is not immediately available. If this flag is specified, the system call will return instantly if it would have to read data from the backing storage or wait for a lock.
If some data was successfully read, it will return the number of bytes read. If no bytes were read, it will return `-1` and set errno to [`errno.EAGAIN`](errno.xhtml#errno.EAGAIN "errno.EAGAIN").
[Availability](intro.xhtml#availability): Linux 4.14 and newer.
3\.7 新版功能.
`os.``RWF_HIPRI`High priority read/write. Allows block-based filesystems to use polling of the device, which provides lower latency, but may use additional resources.
Currently, on Linux, this feature is usable only on a file descriptor opened using the [`O_DIRECT`](#os.O_DIRECT "os.O_DIRECT") flag.
[Availability](intro.xhtml#availability): Linux 4.6 and newer.
3\.7 新版功能.
`os.``pwrite`(*fd*, *str*, *offset*)Write the bytestring in *str* to file descriptor *fd* at position of *offset*, leaving the file offset unchanged.
Return the number of bytes actually written.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``pwritev`(*fd*, *buffers*, *offset*, *flags=0*)Write the *buffers* contents to file descriptor *fd* at a offset *offset*, leaving the file offset unchanged. *buffers* must be a sequence of [bytes-like objects](../glossary.xhtml#term-bytes-like-object). Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.
The flags argument contains a bitwise OR of zero or more of the following flags:
- [`RWF_DSYNC`](#os.RWF_DSYNC "os.RWF_DSYNC")
- [`RWF_SYNC`](#os.RWF_SYNC "os.RWF_SYNC")
Return the total number of bytes actually written.
The operating system may set a limit ([`sysconf()`](#os.sysconf "os.sysconf") value `'SC_IOV_MAX'`) on the number of buffers that can be used.
Combine the functionality of [`os.writev()`](#os.writev "os.writev") and [`os.pwrite()`](#os.pwrite "os.pwrite").
[Availability](intro.xhtml#availability): Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer. Using flags requires Linux 4.7 or newer.
3\.7 新版功能.
`os.``RWF_DSYNC`Provide a per-write equivalent of the [`O_DSYNC`](#os.O_DSYNC "os.O_DSYNC")`open(2)` flag. This flag effect applies only to the data range written by the system call.
[Availability](intro.xhtml#availability): Linux 4.7 and newer.
3\.7 新版功能.
`os.``RWF_SYNC`Provide a per-write equivalent of the [`O_SYNC`](#os.O_SYNC "os.O_SYNC")`open(2)` flag. This flag effect applies only to the data range written by the system call.
[Availability](intro.xhtml#availability): Linux 4.7 and newer.
3\.7 新版功能.
`os.``read`(*fd*, *n*)Read at most *n* bytes from file descriptor *fd*.
Return a bytestring containing the bytes read. If the end of the file referred to by *fd* has been reached, an empty bytes object is returned.
注解
This function is intended for low-level I/O and must be applied to a file descriptor as returned by [`os.open()`](#os.open "os.open") or [`pipe()`](#os.pipe "os.pipe"). To read a "file object" returned by the built-in function [`open()`](functions.xhtml#open "open") or by [`popen()`](#os.popen "os.popen") or [`fdopen()`](#os.fdopen "os.fdopen"), or [`sys.stdin`](sys.xhtml#sys.stdin "sys.stdin"), use its `read()` or `readline()` methods.
在 3.5 版更改: 如果系統調用被中斷,但信號處理程序沒有觸發異常,此函數現在會重試系統調用,而不是觸發 [`InterruptedError`](exceptions.xhtml#InterruptedError "InterruptedError") 異常 (原因詳見 [**PEP 475**](https://www.python.org/dev/peps/pep-0475) \[https://www.python.org/dev/peps/pep-0475\])。
`os.``sendfile`(*out*, *in*, *offset*, *count*)`os.``sendfile`(*out*, *in*, *offset*, *count*, \[*headers*, \]\[*trailers*, \]*flags=0*)Copy *count* bytes from file descriptor *in* to file descriptor *out*starting at *offset*. Return the number of bytes sent. When EOF is reached return 0.
The first function notation is supported by all platforms that define [`sendfile()`](#os.sendfile "os.sendfile").
On Linux, if *offset* is given as `None`, the bytes are read from the current position of *in* and the position of *in* is updated.
The second case may be used on Mac OS X and FreeBSD where *headers* and *trailers* are arbitrary sequences of buffers that are written before and after the data from *in* is written. It returns the same as the first case.
On Mac OS X and FreeBSD, a value of 0 for *count* specifies to send until the end of *in* is reached.
All platforms support sockets as *out* file descriptor, and some platforms allow other types (e.g. regular file, pipe) as well.
Cross-platform applications should not use *headers*, *trailers* and *flags*arguments.
[可用性](intro.xhtml#availability): Unix。
注解
For a higher-level wrapper of [`sendfile()`](#os.sendfile "os.sendfile"), see [`socket.socket.sendfile()`](socket.xhtml#socket.socket.sendfile "socket.socket.sendfile").
3\.3 新版功能.
`os.``set_blocking`(*fd*, *blocking*)Set the blocking mode of the specified file descriptor. Set the [`O_NONBLOCK`](#os.O_NONBLOCK "os.O_NONBLOCK") flag if blocking is `False`, clear the flag otherwise.
See also [`get_blocking()`](#os.get_blocking "os.get_blocking") and [`socket.socket.setblocking()`](socket.xhtml#socket.socket.setblocking "socket.socket.setblocking").
[可用性](intro.xhtml#availability): Unix。
3\.5 新版功能.
`os.``SF_NODISKIO``os.``SF_MNOWAIT``os.``SF_SYNC`Parameters to the [`sendfile()`](#os.sendfile "os.sendfile") function, if the implementation supports them.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``readv`(*fd*, *buffers*)Read from a file descriptor *fd* into a number of mutable [bytes-like objects](../glossary.xhtml#term-bytes-like-object) *buffers*. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.
Return the total number of bytes actually read which can be less than the total capacity of all the objects.
The operating system may set a limit ([`sysconf()`](#os.sysconf "os.sysconf") value `'SC_IOV_MAX'`) on the number of buffers that can be used.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``tcgetpgrp`(*fd*)Return the process group associated with the terminal given by *fd* (an open file descriptor as returned by [`os.open()`](#os.open "os.open")).
[可用性](intro.xhtml#availability): Unix。
`os.``tcsetpgrp`(*fd*, *pg*)Set the process group associated with the terminal given by *fd* (an open file descriptor as returned by [`os.open()`](#os.open "os.open")) to *pg*.
[可用性](intro.xhtml#availability): Unix。
`os.``ttyname`(*fd*)Return a string which specifies the terminal device associated with file descriptor *fd*. If *fd* is not associated with a terminal device, an exception is raised.
[可用性](intro.xhtml#availability): Unix。
`os.``write`(*fd*, *str*)Write the bytestring in *str* to file descriptor *fd*.
Return the number of bytes actually written.
注解
This function is intended for low-level I/O and must be applied to a file descriptor as returned by [`os.open()`](#os.open "os.open") or [`pipe()`](#os.pipe "os.pipe"). To write a "file object" returned by the built-in function [`open()`](functions.xhtml#open "open") or by [`popen()`](#os.popen "os.popen") or [`fdopen()`](#os.fdopen "os.fdopen"), or [`sys.stdout`](sys.xhtml#sys.stdout "sys.stdout") or [`sys.stderr`](sys.xhtml#sys.stderr "sys.stderr"), use its `write()` method.
在 3.5 版更改: 如果系統調用被中斷,但信號處理程序沒有觸發異常,此函數現在會重試系統調用,而不是觸發 [`InterruptedError`](exceptions.xhtml#InterruptedError "InterruptedError") 異常 (原因詳見 [**PEP 475**](https://www.python.org/dev/peps/pep-0475) \[https://www.python.org/dev/peps/pep-0475\])。
`os.``writev`(*fd*, *buffers*)Write the contents of *buffers* to file descriptor *fd*. *buffers* must be a sequence of [bytes-like objects](../glossary.xhtml#term-bytes-like-object). Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.
Returns the total number of bytes actually written.
The operating system may set a limit ([`sysconf()`](#os.sysconf "os.sysconf") value `'SC_IOV_MAX'`) on the number of buffers that can be used.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
### Querying the size of a terminal
3\.3 新版功能.
`os.``get_terminal_size`(*fd=STDOUT\_FILENO*)Return the size of the terminal window as `(columns, lines)`, tuple of type [`terminal_size`](#os.terminal_size "os.terminal_size").
The optional argument `fd` (default `STDOUT_FILENO`, or standard output) specifies which file descriptor should be queried.
If the file descriptor is not connected to a terminal, an [`OSError`](exceptions.xhtml#OSError "OSError")is raised.
[`shutil.get_terminal_size()`](shutil.xhtml#shutil.get_terminal_size "shutil.get_terminal_size") is the high-level function which should normally be used, `os.get_terminal_size` is the low-level implementation.
[可用性](intro.xhtml#availability): Unix, Windows。
*class* `os.``terminal_size`A subclass of tuple, holding `(columns, lines)` of the terminal window size.
`columns`Width of the terminal window in characters.
`lines`Height of the terminal window in characters.
### Inheritance of File Descriptors
3\.4 新版功能.
A file descriptor has an "inheritable" flag which indicates if the file descriptor can be inherited by child processes. Since Python 3.4, file descriptors created by Python are non-inheritable by default.
On UNIX, non-inheritable file descriptors are closed in child processes at the execution of a new program, other file descriptors are inherited.
On Windows, non-inheritable handles and file descriptors are closed in child processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout and stderr), which are always inherited. Using [`spawn*`](#os.spawnl "os.spawnl") functions, all inheritable handles and all inheritable file descriptors are inherited. Using the [`subprocess`](subprocess.xhtml#module-subprocess "subprocess: Subprocess management.") module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the *close\_fds* parameter is `False`.
`os.``get_inheritable`(*fd*)Get the "inheritable" flag of the specified file descriptor (a boolean).
`os.``set_inheritable`(*fd*, *inheritable*)Set the "inheritable" flag of the specified file descriptor.
`os.``get_handle_inheritable`(*handle*)Get the "inheritable" flag of the specified handle (a boolean).
[可用性](intro.xhtml#availability): Windows。
`os.``set_handle_inheritable`(*handle*, *inheritable*)Set the "inheritable" flag of the specified handle.
[可用性](intro.xhtml#availability): Windows。
## Files and Directories
On some Unix platforms, many of these functions support one or more of these features:
- **specifying a file descriptor:**For some functions, the *path* argument can be not only a string giving a path name, but also a file descriptor. The function will then operate on the file referred to by the descriptor. (For POSIX systems, Python will call the `f...` version of the function.)
You can check whether or not *path* can be specified as a file descriptor on your platform using [`os.supports_fd`](#os.supports_fd "os.supports_fd"). If it is unavailable, using it will raise a [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError").
If the function also supports *dir\_fd* or *follow\_symlinks* arguments, it is an error to specify one of those when supplying *path* as a file descriptor.
- **paths relative to directory descriptors:** If *dir\_fd* is not `None`, it should be a file descriptor referring to a directory, and the path to operate on should be relative; path will then be relative to that directory. If the path is absolute, *dir\_fd* is ignored. (For POSIX systems, Python will call the `...at` or `f...at` version of the function.)
You can check whether or not *dir\_fd* is supported on your platform using [`os.supports_dir_fd`](#os.supports_dir_fd "os.supports_dir_fd"). If it is unavailable, using it will raise a [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError").
- **not following symlinks:** If *follow\_symlinks* is `False`, and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself instead of the file the link points to. (For POSIX systems, Python will call the `l...` version of the function.)
You can check whether or not *follow\_symlinks* is supported on your platform using [`os.supports_follow_symlinks`](#os.supports_follow_symlinks "os.supports_follow_symlinks"). If it is unavailable, using it will raise a [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError").
`os.``access`(*path*, *mode*, *\**, *dir\_fd=None*, *effective\_ids=False*, *follow\_symlinks=True*)Use the real uid/gid to test for access to *path*. Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to *path*. *mode* should be [`F_OK`](#os.F_OK "os.F_OK") to test the existence of *path*, or it can be the inclusive OR of one or more of [`R_OK`](#os.R_OK "os.R_OK"), [`W_OK`](#os.W_OK "os.W_OK"), and [`X_OK`](#os.X_OK "os.X_OK") to test permissions. Return [`True`](constants.xhtml#True "True") if access is allowed, [`False`](constants.xhtml#False "False") if not. See the Unix man page *access(2)* for more information.
This function can support specifying [paths relative to directory descriptors](#dir-fd) and [not following symlinks](#follow-symlinks).
If *effective\_ids* is `True`, [`access()`](#os.access "os.access") will perform its access checks using the effective uid/gid instead of the real uid/gid. *effective\_ids* may not be supported on your platform; you can check whether or not it is available using [`os.supports_effective_ids`](#os.supports_effective_ids "os.supports_effective_ids"). If it is unavailable, using it will raise a [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError").
注解
Using [`access()`](#os.access "os.access") to check if a user is authorized to e.g. open a file before actually doing so using [`open()`](functions.xhtml#open "open") creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It's preferable to use [EAFP](../glossary.xhtml#term-eafp)techniques. For example:
```
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
return "some default data"
```
is better written as:
```
try:
fp = open("myfile")
except PermissionError:
return "some default data"
else:
with fp:
return fp.read()
```
注解
I/O operations may fail even when [`access()`](#os.access "os.access") indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.
在 3.3 版更改: Added the *dir\_fd*, *effective\_ids*, and *follow\_symlinks* parameters.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``F_OK``os.``R_OK``os.``W_OK``os.``X_OK`Values to pass as the *mode* parameter of [`access()`](#os.access "os.access") to test the existence, readability, writability and executability of *path*, respectively.
`os.``chdir`(*path*)Change the current working directory to *path*.
This function can support [specifying a file descriptor](#path-fd). The descriptor must refer to an opened directory, not an open file.
3\.3 新版功能: Added support for specifying *path* as a file descriptor on some platforms.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``chflags`(*path*, *flags*, *\**, *follow\_symlinks=True*)Set the flags of *path* to the numeric *flags*. *flags* may take a combination (bitwise OR) of the following values (as defined in the [`stat`](stat.xhtml#module-stat "stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().") module):
- [`stat.UF_NODUMP`](stat.xhtml#stat.UF_NODUMP "stat.UF_NODUMP")
- [`stat.UF_IMMUTABLE`](stat.xhtml#stat.UF_IMMUTABLE "stat.UF_IMMUTABLE")
- [`stat.UF_APPEND`](stat.xhtml#stat.UF_APPEND "stat.UF_APPEND")
- [`stat.UF_OPAQUE`](stat.xhtml#stat.UF_OPAQUE "stat.UF_OPAQUE")
- [`stat.UF_NOUNLINK`](stat.xhtml#stat.UF_NOUNLINK "stat.UF_NOUNLINK")
- [`stat.UF_COMPRESSED`](stat.xhtml#stat.UF_COMPRESSED "stat.UF_COMPRESSED")
- [`stat.UF_HIDDEN`](stat.xhtml#stat.UF_HIDDEN "stat.UF_HIDDEN")
- [`stat.SF_ARCHIVED`](stat.xhtml#stat.SF_ARCHIVED "stat.SF_ARCHIVED")
- [`stat.SF_IMMUTABLE`](stat.xhtml#stat.SF_IMMUTABLE "stat.SF_IMMUTABLE")
- [`stat.SF_APPEND`](stat.xhtml#stat.SF_APPEND "stat.SF_APPEND")
- [`stat.SF_NOUNLINK`](stat.xhtml#stat.SF_NOUNLINK "stat.SF_NOUNLINK")
- [`stat.SF_SNAPSHOT`](stat.xhtml#stat.SF_SNAPSHOT "stat.SF_SNAPSHOT")
This function can support [not following symlinks](#follow-symlinks).
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能: The *follow\_symlinks* argument.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``chmod`(*path*, *mode*, *\**, *dir\_fd=None*, *follow\_symlinks=True*)Change the mode of *path* to the numeric *mode*. *mode* may take one of the following values (as defined in the [`stat`](stat.xhtml#module-stat "stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().") module) or bitwise ORed combinations of them:
- [`stat.S_ISUID`](stat.xhtml#stat.S_ISUID "stat.S_ISUID")
- [`stat.S_ISGID`](stat.xhtml#stat.S_ISGID "stat.S_ISGID")
- [`stat.S_ENFMT`](stat.xhtml#stat.S_ENFMT "stat.S_ENFMT")
- [`stat.S_ISVTX`](stat.xhtml#stat.S_ISVTX "stat.S_ISVTX")
- [`stat.S_IREAD`](stat.xhtml#stat.S_IREAD "stat.S_IREAD")
- [`stat.S_IWRITE`](stat.xhtml#stat.S_IWRITE "stat.S_IWRITE")
- [`stat.S_IEXEC`](stat.xhtml#stat.S_IEXEC "stat.S_IEXEC")
- [`stat.S_IRWXU`](stat.xhtml#stat.S_IRWXU "stat.S_IRWXU")
- [`stat.S_IRUSR`](stat.xhtml#stat.S_IRUSR "stat.S_IRUSR")
- [`stat.S_IWUSR`](stat.xhtml#stat.S_IWUSR "stat.S_IWUSR")
- [`stat.S_IXUSR`](stat.xhtml#stat.S_IXUSR "stat.S_IXUSR")
- [`stat.S_IRWXG`](stat.xhtml#stat.S_IRWXG "stat.S_IRWXG")
- [`stat.S_IRGRP`](stat.xhtml#stat.S_IRGRP "stat.S_IRGRP")
- [`stat.S_IWGRP`](stat.xhtml#stat.S_IWGRP "stat.S_IWGRP")
- [`stat.S_IXGRP`](stat.xhtml#stat.S_IXGRP "stat.S_IXGRP")
- [`stat.S_IRWXO`](stat.xhtml#stat.S_IRWXO "stat.S_IRWXO")
- [`stat.S_IROTH`](stat.xhtml#stat.S_IROTH "stat.S_IROTH")
- [`stat.S_IWOTH`](stat.xhtml#stat.S_IWOTH "stat.S_IWOTH")
- [`stat.S_IXOTH`](stat.xhtml#stat.S_IXOTH "stat.S_IXOTH")
This function can support [specifying a file descriptor](#path-fd), [paths relative to directory descriptors](#dir-fd) and [not following symlinks](#follow-symlinks).
注解
Although Windows supports [`chmod()`](#os.chmod "os.chmod"), you can only set the file's read-only flag with it (via the `stat.S_IWRITE` and `stat.S_IREAD`constants or a corresponding integer value). All other bits are ignored.
3\.3 新版功能: Added support for specifying *path* as an open file descriptor, and the *dir\_fd* and *follow\_symlinks* arguments.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``chown`(*path*, *uid*, *gid*, *\**, *dir\_fd=None*, *follow\_symlinks=True*)Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave one of the ids unchanged, set it to -1.
This function can support [specifying a file descriptor](#path-fd), [paths relative to directory descriptors](#dir-fd) and [not following symlinks](#follow-symlinks).
See [`shutil.chown()`](shutil.xhtml#shutil.chown "shutil.chown") for a higher-level function that accepts names in addition to numeric ids.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能: Added support for specifying an open file descriptor for *path*, and the *dir\_fd* and *follow\_symlinks* arguments.
在 3.6 版更改: Supports a [path-like object](../glossary.xhtml#term-path-like-object).
`os.``chroot`(*path*)Change the root directory of the current process to *path*.
[可用性](intro.xhtml#availability): Unix。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``fchdir`(*fd*)Change the current working directory to the directory represented by the file descriptor *fd*. The descriptor must refer to an opened directory, not an open file. As of Python 3.3, this is equivalent to `os.chdir(fd)`.
[可用性](intro.xhtml#availability): Unix。
`os.``getcwd`()Return a string representing the current working directory.
`os.``getcwdb`()Return a bytestring representing the current working directory.
`os.``lchflags`(*path*, *flags*)Set the flags of *path* to the numeric *flags*, like [`chflags()`](#os.chflags "os.chflags"), but do not follow symbolic links. As of Python 3.3, this is equivalent to `os.chflags(path, flags, follow_symlinks=False)`.
[可用性](intro.xhtml#availability): Unix。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``lchmod`(*path*, *mode*)Change the mode of *path* to the numeric *mode*. If path is a symlink, this affects the symlink rather than the target. See the docs for [`chmod()`](#os.chmod "os.chmod")for possible values of *mode*. As of Python 3.3, this is equivalent to `os.chmod(path, mode, follow_symlinks=False)`.
[可用性](intro.xhtml#availability): Unix。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``lchown`(*path*, *uid*, *gid*)Change the owner and group id of *path* to the numeric *uid* and *gid*. This function will not follow symbolic links. As of Python 3.3, this is equivalent to `os.chown(path, uid, gid, follow_symlinks=False)`.
[可用性](intro.xhtml#availability): Unix。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``link`(*src*, *dst*, *\**, *src\_dir\_fd=None*, *dst\_dir\_fd=None*, *follow\_symlinks=True*)Create a hard link pointing to *src* named *dst*.
This function can support specifying *src\_dir\_fd* and/or *dst\_dir\_fd* to supply [paths relative to directory descriptors](#dir-fd), and [not following symlinks](#follow-symlinks).
[可用性](intro.xhtml#availability): Unix, Windows。
在 3.2 版更改: Added Windows support.
3\.3 新版功能: Added the *src\_dir\_fd*, *dst\_dir\_fd*, and *follow\_symlinks* arguments.
在 3.6 版更改: Accepts a [path-like object](../glossary.xhtml#term-path-like-object) for *src* and *dst*.
`os.``listdir`(*path='.'*)Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory.
*path* may be a [path-like object](../glossary.xhtml#term-path-like-object). If *path* is of type `bytes`(directly or indirectly through the [`PathLike`](#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.
This function can also support [specifying a file descriptor](#path-fd); the file descriptor must refer to a directory.
注解
To encode `str` filenames to `bytes`, use [`fsencode()`](#os.fsencode "os.fsencode").
參見
The [`scandir()`](#os.scandir "os.scandir") function returns directory entries along with file attribute information, giving better performance for many common use cases.
在 3.2 版更改: The *path* parameter became optional.
3\.3 新版功能: Added support for specifying an open file descriptor for *path*.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``lstat`(*path*, *\**, *dir\_fd=None*)Perform the equivalent of an `lstat()` system call on the given path. Similar to [`stat()`](#os.stat "os.stat"), but does not follow symbolic links. Return a [`stat_result`](#os.stat_result "os.stat_result") object.
On platforms that do not support symbolic links, this is an alias for [`stat()`](#os.stat "os.stat").
As of Python 3.3, this is equivalent to
```
os.stat(path, dir_fd=dir_fd,
follow_symlinks=False)
```
.
This function can also support [paths relative to directory descriptors](#dir-fd).
參見
[`stat()`](#os.stat "os.stat") 函數。
在 3.2 版更改: Added support for Windows 6.0 (Vista) symbolic links.
在 3.3 版更改: Added the *dir\_fd* parameter.
在 3.6 版更改: Accepts a [path-like object](../glossary.xhtml#term-path-like-object) for *src* and *dst*.
`os.``mkdir`(*path*, *mode=0o777*, *\**, *dir\_fd=None*)Create a directory named *path* with numeric mode *mode*.
If the directory already exists, [`FileExistsError`](exceptions.xhtml#FileExistsError "FileExistsError") is raised.
On some systems, *mode* is ignored. Where it is used, the current umask value is first masked out. If bits other than the last 9 (i.e. the last 3 digits of the octal representation of the *mode*) are set, their meaning is platform-dependent. On some platforms, they are ignored and you should call [`chmod()`](#os.chmod "os.chmod") explicitly to set them.
This function can also support [paths relative to directory descriptors](#dir-fd).
It is also possible to create temporary directories; see the [`tempfile`](tempfile.xhtml#module-tempfile "tempfile: Generate temporary files and directories.") module's [`tempfile.mkdtemp()`](tempfile.xhtml#tempfile.mkdtemp "tempfile.mkdtemp") function.
3\.3 新版功能: *dir\_fd* 參數。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``makedirs`(*name*, *mode=0o777*, *exist\_ok=False*)Recursive directory creation function. Like [`mkdir()`](#os.mkdir "os.mkdir"), but makes all intermediate-level directories needed to contain the leaf directory.
The *mode* parameter is passed to [`mkdir()`](#os.mkdir "os.mkdir") for creating the leaf directory; see [the mkdir() description](#mkdir-modebits) for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking [`makedirs()`](#os.makedirs "os.makedirs"). The file permission bits of existing parent directories are not changed.
If *exist\_ok* is `False` (the default), an [`OSError`](exceptions.xhtml#OSError "OSError") is raised if the target directory already exists.
注解
[`makedirs()`](#os.makedirs "os.makedirs") will become confused if the path elements to create include [`pardir`](#os.pardir "os.pardir") (eg. ".." on UNIX systems).
This function handles UNC paths correctly.
3\.2 新版功能: The *exist\_ok* parameter.
在 3.4.1 版更改: Before Python 3.4.1, if *exist\_ok* was `True` and the directory existed, [`makedirs()`](#os.makedirs "os.makedirs") would still raise an error if *mode* did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See [bpo-21082](https://bugs.python.org/issue21082) \[https://bugs.python.org/issue21082\].
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
在 3.7 版更改: The *mode* argument no longer affects the file permission bits of newly-created intermediate-level directories.
`os.``mkfifo`(*path*, *mode=0o666*, *\**, *dir\_fd=None*)Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The current umask value is first masked out from the mode.
This function can also support [paths relative to directory descriptors](#dir-fd).
FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with [`os.unlink()`](#os.unlink "os.unlink")). Generally, FIFOs are used as rendezvous between "client" and "server" type processes: the server opens the FIFO for reading, and the client opens it for writing. Note that [`mkfifo()`](#os.mkfifo "os.mkfifo")doesn't open the FIFO --- it just creates the rendezvous point.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能: *dir\_fd* 參數。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``mknod`(*path*, *mode=0o600*, *device=0*, *\**, *dir\_fd=None*)Create a filesystem node (file, device special file or named pipe) named *path*. *mode* specifies both the permissions to use and the type of node to be created, being combined (bitwise OR) with one of `stat.S_IFREG`, `stat.S_IFCHR`, `stat.S_IFBLK`, and `stat.S_IFIFO` (those constants are available in [`stat`](stat.xhtml#module-stat "stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().")). For `stat.S_IFCHR` and `stat.S_IFBLK`, *device* defines the newly created device special file (probably using [`os.makedev()`](#os.makedev "os.makedev")), otherwise it is ignored.
This function can also support [paths relative to directory descriptors](#dir-fd).
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能: *dir\_fd* 參數。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``major`(*device*)Extract the device major number from a raw device number (usually the `st_dev` or `st_rdev` field from `stat`).
`os.``minor`(*device*)Extract the device minor number from a raw device number (usually the `st_dev` or `st_rdev` field from `stat`).
`os.``makedev`(*major*, *minor*)Compose a raw device number from the major and minor device numbers.
`os.``pathconf`(*path*, *name*)Return system configuration information relevant to a named file. *name*specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the `pathconf_names` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted.
If *name* is a string and is not known, [`ValueError`](exceptions.xhtml#ValueError "ValueError") is raised. If a specific value for *name* is not supported by the host system, even if it is included in `pathconf_names`, an [`OSError`](exceptions.xhtml#OSError "OSError") is raised with [`errno.EINVAL`](errno.xhtml#errno.EINVAL "errno.EINVAL") for the error number.
This function can support [specifying a file descriptor](#path-fd).
[可用性](intro.xhtml#availability): Unix。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``pathconf_names`Dictionary mapping names accepted by [`pathconf()`](#os.pathconf "os.pathconf") and [`fpathconf()`](#os.fpathconf "os.fpathconf") to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.
[可用性](intro.xhtml#availability): Unix。
`os.``readlink`(*path*, *\**, *dir\_fd=None*)Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using `os.path.join(os.path.dirname(path), result)`.
If the *path* is a string object (directly or indirectly through a [`PathLike`](#os.PathLike "os.PathLike") interface), the result will also be a string object, and the call may raise a UnicodeDecodeError. If the *path* is a bytes object (direct or indirectly), the result will be a bytes object.
This function can also support [paths relative to directory descriptors](#dir-fd).
[可用性](intro.xhtml#availability): Unix, Windows。
在 3.2 版更改: Added support for Windows 6.0 (Vista) symbolic links.
3\.3 新版功能: *dir\_fd* 參數。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``remove`(*path*, *\**, *dir\_fd=None*)Remove (delete) the file *path*. If *path* is a directory, [`OSError`](exceptions.xhtml#OSError "OSError") is raised. Use [`rmdir()`](#os.rmdir "os.rmdir") to remove directories.
This function can support [paths relative to directory descriptors](#dir-fd).
On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.
This function is semantically identical to [`unlink()`](#os.unlink "os.unlink").
3\.3 新版功能: *dir\_fd* 參數。
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``removedirs`(*name*)Remove directories recursively. Works like [`rmdir()`](#os.rmdir "os.rmdir") except that, if the leaf directory is successfully removed, [`removedirs()`](#os.removedirs "os.removedirs") tries to successively remove every parent directory mentioned in *path* until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, `os.removedirs('foo/bar/baz')` will first remove the directory `'foo/bar/baz'`, and then remove `'foo/bar'` and `'foo'` if they are empty. Raises [`OSError`](exceptions.xhtml#OSError "OSError") if the leaf directory could not be successfully removed.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``rename`(*src*, *dst*, *\**, *src\_dir\_fd=None*, *dst\_dir\_fd=None*)Rename the file or directory *src* to *dst*. If *dst* is a directory, [`OSError`](exceptions.xhtml#OSError "OSError") will be raised. On Unix, if *dst* exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if *src* and *dst* are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if *dst* already exists, [`OSError`](exceptions.xhtml#OSError "OSError") will be raised even if it is a file.
This function can support specifying *src\_dir\_fd* and/or *dst\_dir\_fd* to supply [paths relative to directory descriptors](#dir-fd).
If you want cross-platform overwriting of the destination, use [`replace()`](#os.replace "os.replace").
3\.3 新版功能: The *src\_dir\_fd* and *dst\_dir\_fd* arguments.
在 3.6 版更改: Accepts a [path-like object](../glossary.xhtml#term-path-like-object) for *src* and *dst*.
`os.``renames`(*old*, *new*)Recursive directory or file renaming function. Works like [`rename()`](#os.rename "os.rename"), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using [`removedirs()`](#os.removedirs "os.removedirs").
注解
This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file.
在 3.6 版更改: Accepts a [path-like object](../glossary.xhtml#term-path-like-object) for *old* and *new*.
`os.``replace`(*src*, *dst*, *\**, *src\_dir\_fd=None*, *dst\_dir\_fd=None*)Rename the file or directory *src* to *dst*. If *dst* is a directory, [`OSError`](exceptions.xhtml#OSError "OSError") will be raised. If *dst* exists and is a file, it will be replaced silently if the user has permission. The operation may fail if *src* and *dst* are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).
This function can support specifying *src\_dir\_fd* and/or *dst\_dir\_fd* to supply [paths relative to directory descriptors](#dir-fd).
3\.3 新版功能.
在 3.6 版更改: Accepts a [path-like object](../glossary.xhtml#term-path-like-object) for *src* and *dst*.
`os.``rmdir`(*path*, *\**, *dir\_fd=None*)Remove (delete) the directory *path*. Only works when the directory is empty, otherwise, [`OSError`](exceptions.xhtml#OSError "OSError") is raised. In order to remove whole directory trees, [`shutil.rmtree()`](shutil.xhtml#shutil.rmtree "shutil.rmtree") can be used.
This function can support [paths relative to directory descriptors](#dir-fd).
3\.3 新版功能: The *dir\_fd* parameter.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``scandir`(*path='.'*)Return an iterator of [`os.DirEntry`](#os.DirEntry "os.DirEntry") objects corresponding to the entries in the directory given by *path*. The entries are yielded in arbitrary order, and the special entries `'.'` and `'..'` are not included.
Using [`scandir()`](#os.scandir "os.scandir") instead of [`listdir()`](#os.listdir "os.listdir") can significantly increase the performance of code that also needs file type or file attribute information, because [`os.DirEntry`](#os.DirEntry "os.DirEntry") objects expose this information if the operating system provides it when scanning a directory. All [`os.DirEntry`](#os.DirEntry "os.DirEntry") methods may perform a system call, but [`is_dir()`](#os.DirEntry.is_dir "os.DirEntry.is_dir") and [`is_file()`](#os.DirEntry.is_file "os.DirEntry.is_file") usually only require a system call for symbolic links; [`os.DirEntry.stat()`](#os.DirEntry.stat "os.DirEntry.stat")always requires a system call on Unix but only requires one for symbolic links on Windows.
*path* may be a [path-like object](../glossary.xhtml#term-path-like-object). If *path* is of type `bytes`(directly or indirectly through the [`PathLike`](#os.PathLike "os.PathLike") interface), the type of the [`name`](#os.DirEntry.name "os.DirEntry.name") and [`path`](#os.DirEntry.path "os.DirEntry.path")attributes of each [`os.DirEntry`](#os.DirEntry "os.DirEntry") will be `bytes`; in all other circumstances, they will be of type `str`.
This function can also support [specifying a file descriptor](#path-fd); the file descriptor must refer to a directory.
The [`scandir()`](#os.scandir "os.scandir") iterator supports the [context manager](../glossary.xhtml#term-context-manager) protocol and has the following method:
`scandir.``close`()Close the iterator and free acquired resources.
This is called automatically when the iterator is exhausted or garbage collected, or when an error happens during iterating. However it is advisable to call it explicitly or use the [`with`](../reference/compound_stmts.xhtml#with)statement.
3\.6 新版功能.
The following example shows a simple use of [`scandir()`](#os.scandir "os.scandir") to display all the files (excluding directories) in the given *path* that don't start with `'.'`. The `entry.is_file()` call will generally not make an additional system call:
```
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_file():
print(entry.name)
```
注解
On Unix-based systems, [`scandir()`](#os.scandir "os.scandir") uses the system's [opendir()](http://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html) \[http://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html\]and [readdir()](http://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html) \[http://pubs.opengroup.org/onlinepubs/009695399/functions/readdir\_r.html\]functions. On Windows, it uses the Win32 [FindFirstFileW](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx) \[https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx\]and [FindNextFileW](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx) \[https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx\]functions.
3\.5 新版功能.
3\.6 新版功能: Added support for the [context manager](../glossary.xhtml#term-context-manager) protocol and the [`close()`](#os.scandir.close "os.scandir.close") method. If a [`scandir()`](#os.scandir "os.scandir") iterator is neither exhausted nor explicitly closed a [`ResourceWarning`](exceptions.xhtml#ResourceWarning "ResourceWarning") will be emitted in its destructor.
The function accepts a [path-like object](../glossary.xhtml#term-path-like-object).
在 3.7 版更改: Added support for [file descriptors](#path-fd) on Unix.
*class* `os.``DirEntry`Object yielded by [`scandir()`](#os.scandir "os.scandir") to expose the file path and other file attributes of a directory entry.
[`scandir()`](#os.scandir "os.scandir") will provide as much of this information as possible without making additional system calls. When a `stat()` or `lstat()` system call is made, the `os.DirEntry` object will cache the result.
`os.DirEntry` instances are not intended to be stored in long-lived data structures; if you know the file metadata has changed or if a long time has elapsed since calling [`scandir()`](#os.scandir "os.scandir"), call `os.stat(entry.path)` to fetch up-to-date information.
Because the `os.DirEntry` methods can make operating system calls, they may also raise [`OSError`](exceptions.xhtml#OSError "OSError"). If you need very fine-grained control over errors, you can catch [`OSError`](exceptions.xhtml#OSError "OSError") when calling one of the `os.DirEntry` methods and handle as appropriate.
To be directly usable as a [path-like object](../glossary.xhtml#term-path-like-object), `os.DirEntry`implements the [`PathLike`](#os.PathLike "os.PathLike") interface.
Attributes and methods on a `os.DirEntry` instance are as follows:
`name`The entry's base filename, relative to the [`scandir()`](#os.scandir "os.scandir") *path*argument.
The [`name`](#os.name "os.name") attribute will be `bytes` if the [`scandir()`](#os.scandir "os.scandir")*path* argument is of type `bytes` and `str` otherwise. Use [`fsdecode()`](#os.fsdecode "os.fsdecode") to decode byte filenames.
`path`The entry's full path name: equivalent to
```
os.path.join(scandir_path,
entry.name)
```
where *scandir\_path* is the [`scandir()`](#os.scandir "os.scandir") *path*argument. The path is only absolute if the [`scandir()`](#os.scandir "os.scandir") *path*argument was absolute. If the [`scandir()`](#os.scandir "os.scandir") *path*argument was a [file descriptor](#path-fd), the [`path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.")attribute is the same as the [`name`](#os.name "os.name") attribute.
The [`path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.") attribute will be `bytes` if the [`scandir()`](#os.scandir "os.scandir")*path* argument is of type `bytes` and `str` otherwise. Use [`fsdecode()`](#os.fsdecode "os.fsdecode") to decode byte filenames.
`inode`()Return the inode number of the entry.
The result is cached on the `os.DirEntry` object. Use `os.stat(entry.path, follow_symlinks=False).st_ino` to fetch up-to-date information.
On the first, uncached call, a system call is required on Windows but not on Unix.
`is_dir`(*\**, *follow\_symlinks=True*)Return `True` if this entry is a directory or a symbolic link pointing to a directory; return `False` if the entry is or points to any other kind of file, or if it doesn't exist anymore.
If *follow\_symlinks* is `False`, return `True` only if this entry is a directory (without following symlinks); return `False` if the entry is any other kind of file or if it doesn't exist anymore.
The result is cached on the `os.DirEntry` object, with a separate cache for *follow\_symlinks*`True` and `False`. Call [`os.stat()`](#os.stat "os.stat") along with [`stat.S_ISDIR()`](stat.xhtml#stat.S_ISDIR "stat.S_ISDIR") to fetch up-to-date information.
On the first, uncached call, no system call is required in most cases. Specifically, for non-symlinks, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return `dirent.d_type == DT_UNKNOWN`. If the entry is a symlink, a system call will be required to follow the symlink unless *follow\_symlinks* is `False`.
This method can raise [`OSError`](exceptions.xhtml#OSError "OSError"), such as [`PermissionError`](exceptions.xhtml#PermissionError "PermissionError"), but [`FileNotFoundError`](exceptions.xhtml#FileNotFoundError "FileNotFoundError") is caught and not raised.
`is_file`(*\**, *follow\_symlinks=True*)Return `True` if this entry is a file or a symbolic link pointing to a file; return `False` if the entry is or points to a directory or other non-file entry, or if it doesn't exist anymore.
If *follow\_symlinks* is `False`, return `True` only if this entry is a file (without following symlinks); return `False` if the entry is a directory or other non-file entry, or if it doesn't exist anymore.
The result is cached on the `os.DirEntry` object. Caching, system calls made, and exceptions raised are as per [`is_dir()`](#os.DirEntry.is_dir "os.DirEntry.is_dir").
`is_symlink`()Return `True` if this entry is a symbolic link (even if broken); return `False` if the entry points to a directory or any kind of file, or if it doesn't exist anymore.
The result is cached on the `os.DirEntry` object. Call [`os.path.islink()`](os.path.xhtml#os.path.islink "os.path.islink") to fetch up-to-date information.
On the first, uncached call, no system call is required in most cases. Specifically, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return `dirent.d_type == DT_UNKNOWN`.
This method can raise [`OSError`](exceptions.xhtml#OSError "OSError"), such as [`PermissionError`](exceptions.xhtml#PermissionError "PermissionError"), but [`FileNotFoundError`](exceptions.xhtml#FileNotFoundError "FileNotFoundError") is caught and not raised.
`stat`(*\**, *follow\_symlinks=True*)Return a [`stat_result`](#os.stat_result "os.stat_result") object for this entry. This method follows symbolic links by default; to stat a symbolic link add the `follow_symlinks=False` argument.
On Unix, this method always requires a system call. On Windows, it only requires a system call if *follow\_symlinks* is `True` and the entry is a symbolic link.
On Windows, the `st_ino`, `st_dev` and `st_nlink` attributes of the [`stat_result`](#os.stat_result "os.stat_result") are always set to zero. Call [`os.stat()`](#os.stat "os.stat") to get these attributes.
The result is cached on the `os.DirEntry` object, with a separate cache for *follow\_symlinks*`True` and `False`. Call [`os.stat()`](#os.stat "os.stat") to fetch up-to-date information.
Note that there is a nice correspondence between several attributes and methods of `os.DirEntry` and of [`pathlib.Path`](pathlib.xhtml#pathlib.Path "pathlib.Path"). In particular, the `name` attribute has the same meaning, as do the `is_dir()`, `is_file()`, `is_symlink()`and `stat()` methods.
3\.5 新版功能.
在 3.6 版更改: Added support for the [`PathLike`](#os.PathLike "os.PathLike") interface. Added support for [`bytes`](stdtypes.xhtml#bytes "bytes") paths on Windows.
`os.``stat`(*path*, *\**, *dir\_fd=None*, *follow\_symlinks=True*)Get the status of a file or a file descriptor. Perform the equivalent of a `stat()` system call on the given path. *path* may be specified as either a string or bytes -- directly or indirectly through the [`PathLike`](#os.PathLike "os.PathLike")interface -- or as an open file descriptor. Return a [`stat_result`](#os.stat_result "os.stat_result")object.
This function normally follows symlinks; to stat a symlink add the argument `follow_symlinks=False`, or use [`lstat()`](#os.lstat "os.lstat").
This function can support [specifying a file descriptor](#path-fd) and [not following symlinks](#follow-symlinks).
示例:
```
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
```
參見
[`fstat()`](#os.fstat "os.fstat") and [`lstat()`](#os.lstat "os.lstat") functions.
3\.3 新版功能: Added the *dir\_fd* and *follow\_symlinks* arguments, specifying a file descriptor instead of a path.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
*class* `os.``stat_result`Object whose attributes correspond roughly to the members of the `stat` structure. It is used for the result of [`os.stat()`](#os.stat "os.stat"), [`os.fstat()`](#os.fstat "os.fstat") and [`os.lstat()`](#os.lstat "os.lstat").
Attributes:
`st_mode`File mode: file type and file mode bits (permissions).
`st_ino`Platform dependent, but if non-zero, uniquely identifies the file for a given value of `st_dev`. Typically:
- the inode number on Unix,
- the [file index](https://msdn.microsoft.com/en-us/library/aa363788) \[https://msdn.microsoft.com/en-us/library/aa363788\] on Windows
`st_dev`Identifier of the device on which this file resides.
`st_nlink`Number of hard links.
`st_uid`User identifier of the file owner.
`st_gid`Group identifier of the file owner.
`st_size`Size of the file in bytes, if it is a regular file or a symbolic link. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.
Timestamps:
`st_atime`Time of most recent access expressed in seconds.
`st_mtime`Time of most recent content modification expressed in seconds.
`st_ctime`Platform dependent:
- the time of most recent metadata change on Unix,
- the time of creation on Windows, expressed in seconds.
`st_atime_ns`Time of most recent access expressed in nanoseconds as an integer.
`st_mtime_ns`Time of most recent content modification expressed in nanoseconds as an integer.
`st_ctime_ns`Platform dependent:
- the time of most recent metadata change on Unix,
- the time of creation on Windows, expressed in nanoseconds as an integer.
注解
The exact meaning and resolution of the [`st_atime`](#os.stat_result.st_atime "os.stat_result.st_atime"), [`st_mtime`](#os.stat_result.st_mtime "os.stat_result.st_mtime"), and [`st_ctime`](#os.stat_result.st_ctime "os.stat_result.st_ctime") attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, [`st_mtime`](#os.stat_result.st_mtime "os.stat_result.st_mtime") has 2-second resolution, and [`st_atime`](#os.stat_result.st_atime "os.stat_result.st_atime") has only 1-day resolution. See your operating system documentation for details.
Similarly, although [`st_atime_ns`](#os.stat_result.st_atime_ns "os.stat_result.st_atime_ns"), [`st_mtime_ns`](#os.stat_result.st_mtime_ns "os.stat_result.st_mtime_ns"), and [`st_ctime_ns`](#os.stat_result.st_ctime_ns "os.stat_result.st_ctime_ns") are always expressed in nanoseconds, many systems do not provide nanosecond precision. On systems that do provide nanosecond precision, the floating-point object used to store [`st_atime`](#os.stat_result.st_atime "os.stat_result.st_atime"), [`st_mtime`](#os.stat_result.st_mtime "os.stat_result.st_mtime"), and [`st_ctime`](#os.stat_result.st_ctime "os.stat_result.st_ctime")cannot preserve all of it, and as such will be slightly inexact. If you need the exact timestamps you should always use [`st_atime_ns`](#os.stat_result.st_atime_ns "os.stat_result.st_atime_ns"), [`st_mtime_ns`](#os.stat_result.st_mtime_ns "os.stat_result.st_mtime_ns"), and [`st_ctime_ns`](#os.stat_result.st_ctime_ns "os.stat_result.st_ctime_ns").
On some Unix systems (such as Linux), the following attributes may also be available:
`st_blocks`Number of 512-byte blocks allocated for file. This may be smaller than [`st_size`](#os.stat_result.st_size "os.stat_result.st_size")/512 when the file has holes.
`st_blksize`"Preferred" blocksize for efficient file system I/O. Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.
`st_rdev`Type of device if an inode device.
`st_flags`User defined flags for file.
On other Unix systems (such as FreeBSD), the following attributes may be available (but may be only filled out if root tries to use them):
`st_gen`File generation number.
`st_birthtime`Time of file creation.
On Solaris and derivatives, the following attributes may also be available:
`st_fstype`String that uniquely identifies the type of the filesystem that contains the file.
On Mac OS systems, the following attributes may also be available:
`st_rsize`Real size of the file.
`st_creator`Creator of the file.
`st_type`File type.
On Windows systems, the following attribute is also available:
`st_file_attributes`Windows file attributes: `dwFileAttributes` member of the `BY_HANDLE_FILE_INFORMATION` structure returned by `GetFileInformationByHandle()`. See the `FILE_ATTRIBUTE_*`constants in the [`stat`](stat.xhtml#module-stat "stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().") module.
The standard module [`stat`](stat.xhtml#module-stat "stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().") defines functions and constants that are useful for extracting information from a `stat` structure. (On Windows, some items are filled with dummy values.)
For backward compatibility, a [`stat_result`](#os.stat_result "os.stat_result") instance is also accessible as a tuple of at least 10 integers giving the most important (and portable) members of the `stat` structure, in the order [`st_mode`](#os.stat_result.st_mode "os.stat_result.st_mode"), [`st_ino`](#os.stat_result.st_ino "os.stat_result.st_ino"), [`st_dev`](#os.stat_result.st_dev "os.stat_result.st_dev"), [`st_nlink`](#os.stat_result.st_nlink "os.stat_result.st_nlink"), [`st_uid`](#os.stat_result.st_uid "os.stat_result.st_uid"), [`st_gid`](#os.stat_result.st_gid "os.stat_result.st_gid"), [`st_size`](#os.stat_result.st_size "os.stat_result.st_size"), [`st_atime`](#os.stat_result.st_atime "os.stat_result.st_atime"), [`st_mtime`](#os.stat_result.st_mtime "os.stat_result.st_mtime"), [`st_ctime`](#os.stat_result.st_ctime "os.stat_result.st_ctime"). More items may be added at the end by some implementations. For compatibility with older Python versions, accessing [`stat_result`](#os.stat_result "os.stat_result") as a tuple always returns integers.
3\.3 新版功能: Added the [`st_atime_ns`](#os.stat_result.st_atime_ns "os.stat_result.st_atime_ns"), [`st_mtime_ns`](#os.stat_result.st_mtime_ns "os.stat_result.st_mtime_ns"), and [`st_ctime_ns`](#os.stat_result.st_ctime_ns "os.stat_result.st_ctime_ns") members.
3\.5 新版功能: Added the [`st_file_attributes`](#os.stat_result.st_file_attributes "os.stat_result.st_file_attributes") member on Windows.
在 3.5 版更改: Windows now returns the file index as [`st_ino`](#os.stat_result.st_ino "os.stat_result.st_ino") when available.
3\.7 新版功能: Added the [`st_fstype`](#os.stat_result.st_fstype "os.stat_result.st_fstype") member to Solaris/derivatives.
`os.``statvfs`(*path*)Perform a `statvfs()` system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the `statvfs` structure, namely: `f_bsize`, `f_frsize`, `f_blocks`, `f_bfree`, `f_bavail`, `f_files`, `f_ffree`, `f_favail`, `f_flag`, `f_namemax`, `f_fsid`.
Two module-level constants are defined for the `f_flag` attribute's bit-flags: if `ST_RDONLY` is set, the filesystem is mounted read-only, and if `ST_NOSUID` is set, the semantics of setuid/setgid bits are disabled or not supported.
Additional module-level constants are defined for GNU/glibc based systems. These are `ST_NODEV` (disallow access to device special files), `ST_NOEXEC` (disallow program execution), `ST_SYNCHRONOUS`(writes are synced at once), `ST_MANDLOCK` (allow mandatory locks on an FS), `ST_WRITE` (write on file/directory/symlink), `ST_APPEND`(append-only file), `ST_IMMUTABLE` (immutable file), `ST_NOATIME`(do not update access times), `ST_NODIRATIME` (do not update directory access times), `ST_RELATIME` (update atime relative to mtime/ctime).
This function can support [specifying a file descriptor](#path-fd).
[可用性](intro.xhtml#availability): Unix。
在 3.2 版更改: The `ST_RDONLY` and `ST_NOSUID` constants were added.
3\.3 新版功能: Added support for specifying an open file descriptor for *path*.
在 3.4 版更改: The `ST_NODEV`, `ST_NOEXEC`, `ST_SYNCHRONOUS`, `ST_MANDLOCK`, `ST_WRITE`, `ST_APPEND`, `ST_IMMUTABLE`, `ST_NOATIME`, `ST_NODIRATIME`, and `ST_RELATIME` constants were added.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
3\.7 新版功能: Added `f_fsid`.
`os.``supports_dir_fd`A [`Set`](collections.abc.xhtml#collections.abc.Set "collections.abc.Set") object indicating which functions in the [`os`](#module-os "os: Miscellaneous operating system interfaces.") module permit use of their *dir\_fd* parameter. Different platforms provide different functionality, and an option that might work on one might be unsupported on another. For consistency's sakes, functions that support *dir\_fd* always allow specifying the parameter, but will raise an exception if the functionality is not actually available.
To check whether a particular function permits use of its *dir\_fd*parameter, use the `in` operator on `supports_dir_fd`. As an example, this expression determines whether the *dir\_fd* parameter of [`os.stat()`](#os.stat "os.stat")is locally available:
```
os.stat in os.supports_dir_fd
```
Currently *dir\_fd* parameters only work on Unix platforms; none of them work on Windows.
3\.3 新版功能.
`os.``supports_effective_ids`A [`Set`](collections.abc.xhtml#collections.abc.Set "collections.abc.Set") object indicating which functions in the [`os`](#module-os "os: Miscellaneous operating system interfaces.") module permit use of the *effective\_ids* parameter for [`os.access()`](#os.access "os.access"). If the local platform supports it, the collection will contain [`os.access()`](#os.access "os.access"), otherwise it will be empty.
To check whether you can use the *effective\_ids* parameter for [`os.access()`](#os.access "os.access"), use the `in` operator on `supports_effective_ids`, like so:
```
os.access in os.supports_effective_ids
```
Currently *effective\_ids* only works on Unix platforms; it does not work on Windows.
3\.3 新版功能.
`os.``supports_fd`A [`Set`](collections.abc.xhtml#collections.abc.Set "collections.abc.Set") object indicating which functions in the [`os`](#module-os "os: Miscellaneous operating system interfaces.") module permit specifying their *path* parameter as an open file descriptor. Different platforms provide different functionality, and an option that might work on one might be unsupported on another. For consistency's sakes, functions that support *fd* always allow specifying the parameter, but will raise an exception if the functionality is not actually available.
To check whether a particular function permits specifying an open file descriptor for its *path* parameter, use the `in` operator on `supports_fd`. As an example, this expression determines whether [`os.chdir()`](#os.chdir "os.chdir") accepts open file descriptors when called on your local platform:
```
os.chdir in os.supports_fd
```
3\.3 新版功能.
`os.``supports_follow_symlinks`A [`Set`](collections.abc.xhtml#collections.abc.Set "collections.abc.Set") object indicating which functions in the [`os`](#module-os "os: Miscellaneous operating system interfaces.") module permit use of their *follow\_symlinks* parameter. Different platforms provide different functionality, and an option that might work on one might be unsupported on another. For consistency's sakes, functions that support *follow\_symlinks* always allow specifying the parameter, but will raise an exception if the functionality is not actually available.
To check whether a particular function permits use of its *follow\_symlinks*parameter, use the `in` operator on `supports_follow_symlinks`. As an example, this expression determines whether the *follow\_symlinks* parameter of [`os.stat()`](#os.stat "os.stat") is locally available:
```
os.stat in os.supports_follow_symlinks
```
3\.3 新版功能.
`os.``symlink`(*src*, *dst*, *target\_is\_directory=False*, *\**, *dir\_fd=None*)Create a symbolic link pointing to *src* named *dst*.
On Windows, a symlink represents either a file or a directory, and does not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if *target\_is\_directory* is `True` or a file symlink (the default) otherwise. On non-Windows platforms, *target\_is\_directory* is ignored.
Symbolic link support was introduced in Windows 6.0 (Vista). [`symlink()`](#os.symlink "os.symlink")will raise a [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError") on Windows versions earlier than 6.0.
This function can support [paths relative to directory descriptors](#dir-fd).
注解
On Windows, the *SeCreateSymbolicLinkPrivilege* is required in order to successfully create symlinks. This privilege is not typically granted to regular users but is available to accounts which can escalate privileges to the administrator level. Either obtaining the privilege or running your application as an administrator are ways to successfully create symlinks.
[`OSError`](exceptions.xhtml#OSError "OSError") is raised when the function is called by an unprivileged user.
[可用性](intro.xhtml#availability): Unix, Windows。
在 3.2 版更改: Added support for Windows 6.0 (Vista) symbolic links.
3\.3 新版功能: Added the *dir\_fd* argument, and now allow *target\_is\_directory*on non-Windows platforms.
在 3.6 版更改: Accepts a [path-like object](../glossary.xhtml#term-path-like-object) for *src* and *dst*.
`os.``sync`()Force write of everything to disk.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``truncate`(*path*, *length*)Truncate the file corresponding to *path*, so that it is at most *length* bytes in size.
This function can support [specifying a file descriptor](#path-fd).
[可用性](intro.xhtml#availability): Unix, Windows。
3\.3 新版功能.
在 3.5 版更改: 添加了 Windows 支持
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``unlink`(*path*, *\**, *dir\_fd=None*)Remove (delete) the file *path*. This function is semantically identical to [`remove()`](#os.remove "os.remove"); the `unlink` name is its traditional Unix name. Please see the documentation for [`remove()`](#os.remove "os.remove") for further information.
3\.3 新版功能: The *dir\_fd* parameter.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``utime`(*path*, *times=None*, *\**, \[*ns*, \]*dir\_fd=None*, *follow\_symlinks=True*)Set the access and modified times of the file specified by *path*.
[`utime()`](#os.utime "os.utime") takes two optional parameters, *times* and *ns*. These specify the times set on *path* and are used as follows:
- If *ns* is specified, it must be a 2-tuple of the form `(atime_ns, mtime_ns)`where each member is an int expressing nanoseconds.
- If *times* is not `None`, it must be a 2-tuple of the form `(atime, mtime)`where each member is an int or float expressing seconds.
- If *times* is `None` and *ns* is unspecified, this is equivalent to specifying `ns=(atime_ns, mtime_ns)`where both times are the current time.
It is an error to specify tuples for both *times* and *ns*.
Whether a directory can be given for *path*depends on whether the operating system implements directories as files (for example, Windows does not). Note that the exact times you set here may not be returned by a subsequent [`stat()`](#os.stat "os.stat") call, depending on the resolution with which your operating system records access and modification times; see [`stat()`](#os.stat "os.stat"). The best way to preserve exact times is to use the *st\_atime\_ns* and *st\_mtime\_ns* fields from the [`os.stat()`](#os.stat "os.stat")result object with the *ns* parameter to utime.
This function can support [specifying a file descriptor](#path-fd), [paths relative to directory descriptors](#dir-fd) and [not following symlinks](#follow-symlinks).
3\.3 新版功能: Added support for specifying an open file descriptor for *path*, and the *dir\_fd*, *follow\_symlinks*, and *ns* parameters.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``walk`(*top*, *topdown=True*, *onerror=None*, *followlinks=False*)Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory *top* (including *top* itself), it yields a 3-tuple
```
(dirpath, dirnames,
filenames)
```
.
*dirpath* is a string, the path to the directory. *dirnames* is a list of the names of the subdirectories in *dirpath* (excluding `'.'` and `'..'`). *filenames* is a list of the names of the non-directory files in *dirpath*. Note that the names in the lists contain no path components. To get a full path (which begins with *top*) to a file or directory in *dirpath*, do `os.path.join(dirpath, name)`.
If optional argument *topdown* is `True` or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If *topdown* is `False`, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of *topdown*, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.
When *topdown* is `True`, the caller can modify the *dirnames* list in-place (perhaps using [`del`](../reference/simple_stmts.xhtml#del) or slice assignment), and [`walk()`](#os.walk "os.walk") will only recurse into the subdirectories whose names remain in *dirnames*; this can be used to prune the search, impose a specific order of visiting, or even to inform [`walk()`](#os.walk "os.walk") about directories the caller creates or renames before it resumes [`walk()`](#os.walk "os.walk") again. Modifying *dirnames* when *topdown* is `False` has no effect on the behavior of the walk, because in bottom-up mode the directories in *dirnames* are generated before *dirpath* itself is generated.
By default, errors from the [`scandir()`](#os.scandir "os.scandir") call are ignored. If optional argument *onerror* is specified, it should be a function; it will be called with one argument, an [`OSError`](exceptions.xhtml#OSError "OSError") instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the `filename` attribute of the exception object.
By default, [`walk()`](#os.walk "os.walk") will not walk down into symbolic links that resolve to directories. Set *followlinks* to `True` to visit directories pointed to by symlinks, on systems that support them.
注解
Be aware that setting *followlinks* to `True` can lead to infinite recursion if a link points to a parent directory of itself. [`walk()`](#os.walk "os.walk")does not keep track of the directories it visited already.
注解
If you pass a relative pathname, don't change the current working directory between resumptions of [`walk()`](#os.walk "os.walk"). [`walk()`](#os.walk "os.walk") never changes the current directory, and assumes that its caller doesn't either.
This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn't look under any CVS subdirectory:
```
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print(root, "consumes", end=" ")
print(sum(getsize(join(root, name)) for name in files), end=" ")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
```
In the next example (simple implementation of [`shutil.rmtree()`](shutil.xhtml#shutil.rmtree "shutil.rmtree")), walking the tree bottom-up is essential, [`rmdir()`](#os.rmdir "os.rmdir") doesn't allow deleting a directory before the directory is empty:
```
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
```
在 3.5 版更改: This function now calls [`os.scandir()`](#os.scandir "os.scandir") instead of [`os.listdir()`](#os.listdir "os.listdir"), making it faster by reducing the number of calls to [`os.stat()`](#os.stat "os.stat").
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``fwalk`(*top='.'*, *topdown=True*, *onerror=None*, *\**, *follow\_symlinks=False*, *dir\_fd=None*)This behaves exactly like [`walk()`](#os.walk "os.walk"), except that it yields a 4-tuple `(dirpath, dirnames, filenames, dirfd)`, and it supports `dir_fd`.
*dirpath*, *dirnames* and *filenames* are identical to [`walk()`](#os.walk "os.walk") output, and *dirfd* is a file descriptor referring to the directory *dirpath*.
This function always supports [paths relative to directory descriptors](#dir-fd) and [not following symlinks](#follow-symlinks). Note however that, unlike other functions, the [`fwalk()`](#os.fwalk "os.fwalk") default value for *follow\_symlinks* is `False`.
注解
Since [`fwalk()`](#os.fwalk "os.fwalk") yields file descriptors, those are only valid until the next iteration step, so you should duplicate them (e.g. with [`dup()`](#os.dup "os.dup")) if you want to keep them longer.
This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn't look under any CVS subdirectory:
```
import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
print(root, "consumes", end="")
print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
end="")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
```
In the next example, walking the tree bottom-up is essential: [`rmdir()`](#os.rmdir "os.rmdir") doesn't allow deleting a directory before the directory is empty:
```
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
for name in files:
os.unlink(name, dir_fd=rootfd)
for name in dirs:
os.rmdir(name, dir_fd=rootfd)
```
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
在 3.7 版更改: Added support for [`bytes`](stdtypes.xhtml#bytes "bytes") paths.
### Linux extended attributes
3\.3 新版功能.
These functions are all available on Linux only.
`os.``getxattr`(*path*, *attribute*, *\**, *follow\_symlinks=True*)Return the value of the extended filesystem attribute *attribute* for *path*. *attribute* can be bytes or str (directly or indirectly through the [`PathLike`](#os.PathLike "os.PathLike") interface). If it is str, it is encoded with the filesystem encoding.
This function can support [specifying a file descriptor](#path-fd) and [not following symlinks](#follow-symlinks).
在 3.6 版更改: Accepts a [path-like object](../glossary.xhtml#term-path-like-object) for *path* and *attribute*.
`os.``listxattr`(*path=None*, *\**, *follow\_symlinks=True*)Return a list of the extended filesystem attributes on *path*. The attributes in the list are represented as strings decoded with the filesystem encoding. If *path* is `None`, [`listxattr()`](#os.listxattr "os.listxattr") will examine the current directory.
This function can support [specifying a file descriptor](#path-fd) and [not following symlinks](#follow-symlinks).
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``removexattr`(*path*, *attribute*, *\**, *follow\_symlinks=True*)Removes the extended filesystem attribute *attribute* from *path*. *attribute* should be bytes or str (directly or indirectly through the [`PathLike`](#os.PathLike "os.PathLike") interface). If it is a string, it is encoded with the filesystem encoding.
This function can support [specifying a file descriptor](#path-fd) and [not following symlinks](#follow-symlinks).
在 3.6 版更改: Accepts a [path-like object](../glossary.xhtml#term-path-like-object) for *path* and *attribute*.
`os.``setxattr`(*path*, *attribute*, *value*, *flags=0*, *\**, *follow\_symlinks=True*)Set the extended filesystem attribute *attribute* on *path* to *value*. *attribute* must be a bytes or str with no embedded NULs (directly or indirectly through the [`PathLike`](#os.PathLike "os.PathLike") interface). If it is a str, it is encoded with the filesystem encoding. *flags* may be [`XATTR_REPLACE`](#os.XATTR_REPLACE "os.XATTR_REPLACE") or [`XATTR_CREATE`](#os.XATTR_CREATE "os.XATTR_CREATE"). If [`XATTR_REPLACE`](#os.XATTR_REPLACE "os.XATTR_REPLACE") is given and the attribute does not exist, `EEXISTS` will be raised. If [`XATTR_CREATE`](#os.XATTR_CREATE "os.XATTR_CREATE") is given and the attribute already exists, the attribute will not be created and `ENODATA` will be raised.
This function can support [specifying a file descriptor](#path-fd) and [not following symlinks](#follow-symlinks).
注解
A bug in Linux kernel versions less than 2.6.39 caused the flags argument to be ignored on some filesystems.
在 3.6 版更改: Accepts a [path-like object](../glossary.xhtml#term-path-like-object) for *path* and *attribute*.
`os.``XATTR_SIZE_MAX`The maximum size the value of an extended attribute can be. Currently, this is 64 KiB on Linux.
`os.``XATTR_CREATE`This is a possible value for the flags argument in [`setxattr()`](#os.setxattr "os.setxattr"). It indicates the operation must create an attribute.
`os.``XATTR_REPLACE`This is a possible value for the flags argument in [`setxattr()`](#os.setxattr "os.setxattr"). It indicates the operation must replace an existing attribute.
## Process Management
These functions may be used to create and manage processes.
The various [`exec*`](#os.execl "os.execl") functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this is the `argv[0]`passed to a program's `main()`. For example,
```
os.execv('/bin/echo',
['foo', 'bar'])
```
will only print `bar` on standard output; `foo` will seem to be ignored.
`os.``abort`()Generate a `SIGABRT` signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns an exit code of `3`. Be aware that calling this function will not call the Python signal handler registered for `SIGABRT` with [`signal.signal()`](signal.xhtml#signal.signal "signal.signal").
`os.``execl`(*path*, *arg0*, *arg1*, *...*)`os.``execle`(*path*, *arg0*, *arg1*, *...*, *env*)`os.``execlp`(*file*, *arg0*, *arg1*, *...*)`os.``execlpe`(*file*, *arg0*, *arg1*, *...*, *env*)`os.``execv`(*path*, *args*)`os.``execve`(*path*, *args*, *env*)`os.``execvp`(*file*, *args*)`os.``execvpe`(*file*, *args*, *env*)These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as [`OSError`](exceptions.xhtml#OSError "OSError") exceptions.
The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using `sys.stdout.flush()` or [`os.fsync()`](#os.fsync "os.fsync") before calling an [`exec*`](#os.execl "os.execl") function.
The "l" and "v" variants of the [`exec*`](#os.execl "os.execl") functions differ in how command-line arguments are passed. The "l" variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the `execl*()`functions. The "v" variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the *args*parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced.
The variants which include a "p" near the end ([`execlp()`](#os.execlp "os.execlp"), [`execlpe()`](#os.execlpe "os.execlpe"), [`execvp()`](#os.execvp "os.execvp"), and [`execvpe()`](#os.execvpe "os.execvpe")) will use the `PATH` environment variable to locate the program *file*. When the environment is being replaced (using one of the [`exec*e`](#os.execl "os.execl") variants, discussed in the next paragraph), the new environment is used as the source of the `PATH` variable. The other variants, [`execl()`](#os.execl "os.execl"), [`execle()`](#os.execle "os.execle"), [`execv()`](#os.execv "os.execv"), and [`execve()`](#os.execve "os.execve"), will not use the `PATH` variable to locate the executable; *path* must contain an appropriate absolute or relative path.
For [`execle()`](#os.execle "os.execle"), [`execlpe()`](#os.execlpe "os.execlpe"), [`execve()`](#os.execve "os.execve"), and [`execvpe()`](#os.execvpe "os.execvpe") (note that these all end in "e"), the *env* parameter must be a mapping which is used to define the environment variables for the new process (these are used instead of the current process' environment); the functions [`execl()`](#os.execl "os.execl"), [`execlp()`](#os.execlp "os.execlp"), [`execv()`](#os.execv "os.execv"), and [`execvp()`](#os.execvp "os.execvp") all cause the new process to inherit the environment of the current process.
For [`execve()`](#os.execve "os.execve") on some platforms, *path* may also be specified as an open file descriptor. This functionality may not be supported on your platform; you can check whether or not it is available using [`os.supports_fd`](#os.supports_fd "os.supports_fd"). If it is unavailable, using it will raise a [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError").
[可用性](intro.xhtml#availability): Unix, Windows。
3\.3 新版功能: Added support for specifying an open file descriptor for *path*for [`execve()`](#os.execve "os.execve").
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``_exit`(*n*)Exit the process with status *n*, without calling cleanup handlers, flushing stdio buffers, etc.
注解
The standard way to exit is `sys.exit(n)`. [`_exit()`](#os._exit "os._exit") should normally only be used in the child process after a [`fork()`](#os.fork "os.fork").
The following exit codes are defined and can be used with [`_exit()`](#os._exit "os._exit"), although they are not required. These are typically used for system programs written in Python, such as a mail server's external command delivery program.
注解
Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.
`os.``EX_OK`Exit code that means no error occurred.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_USAGE`Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_DATAERR`Exit code that means the input data was incorrect.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_NOINPUT`Exit code that means an input file did not exist or was not readable.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_NOUSER`Exit code that means a specified user did not exist.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_NOHOST`Exit code that means a specified host did not exist.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_UNAVAILABLE`Exit code that means that a required service is unavailable.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_SOFTWARE`Exit code that means an internal software error was detected.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_OSERR`Exit code that means an operating system error was detected, such as the inability to fork or create a pipe.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_OSFILE`Exit code that means some system file did not exist, could not be opened, or had some other kind of error.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_CANTCREAT`Exit code that means a user specified output file could not be created.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_IOERR`Exit code that means that an error occurred while doing I/O on some file.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_TEMPFAIL`Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn't be made during a retryable operation.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_PROTOCOL`Exit code that means that a protocol exchange was illegal, invalid, or not understood.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_NOPERM`Exit code that means that there were insufficient permissions to perform the operation (but not intended for file system problems).
[可用性](intro.xhtml#availability): Unix。
`os.``EX_CONFIG`Exit code that means that some kind of configuration error occurred.
[可用性](intro.xhtml#availability): Unix。
`os.``EX_NOTFOUND`Exit code that means something like "an entry was not found".
[可用性](intro.xhtml#availability): Unix。
`os.``fork`()Fork a child process. Return `0` in the child and the child's process id in the parent. If an error occurs [`OSError`](exceptions.xhtml#OSError "OSError") is raised.
Note that some platforms including FreeBSD <= 6.3 and Cygwin have known issues when using fork() from a thread.
警告
See [`ssl`](ssl.xhtml#module-ssl "ssl: TLS/SSL wrapper for socket objects") for applications that use the SSL module with fork().
[可用性](intro.xhtml#availability): Unix。
`os.``forkpty`()Fork a child process, using a new pseudo-terminal as the child's controlling terminal. Return a pair of `(pid, fd)`, where *pid* is `0` in the child, the new child's process id in the parent, and *fd* is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the [`pty`](pty.xhtml#module-pty "pty: Pseudo-Terminal Handling for Linux. (Linux)") module. If an error occurs [`OSError`](exceptions.xhtml#OSError "OSError") is raised.
[可用性](intro.xhtml#availability): 某些 Unix。
`os.``kill`(*pid*, *sig*)Send signal *sig* to the process *pid*. Constants for the specific signals available on the host platform are defined in the [`signal`](signal.xhtml#module-signal "signal: Set handlers for asynchronous events.") module.
Windows: The [`signal.CTRL_C_EVENT`](signal.xhtml#signal.CTRL_C_EVENT "signal.CTRL_C_EVENT") and [`signal.CTRL_BREAK_EVENT`](signal.xhtml#signal.CTRL_BREAK_EVENT "signal.CTRL_BREAK_EVENT") signals are special signals which can only be sent to console processes which share a common console window, e.g., some subprocesses. Any other value for *sig* will cause the process to be unconditionally killed by the TerminateProcess API, and the exit code will be set to *sig*. The Windows version of [`kill()`](#os.kill "os.kill") additionally takes process handles to be killed.
See also [`signal.pthread_kill()`](signal.xhtml#signal.pthread_kill "signal.pthread_kill").
3\.2 新版功能: Windows support.
`os.``killpg`(*pgid*, *sig*)Send the signal *sig* to the process group *pgid*.
[可用性](intro.xhtml#availability): Unix。
`os.``nice`(*increment*)Add *increment* to the process's "niceness". Return the new niceness.
[可用性](intro.xhtml#availability): Unix。
`os.``plock`(*op*)Lock program segments into memory. The value of *op* (defined in `<sys/lock.h>`) determines which segments are locked.
[可用性](intro.xhtml#availability): Unix。
`os.``popen`(*cmd*, *mode='r'*, *buffering=-1*)Open a pipe to or from command *cmd*. The return value is an open file object connected to the pipe, which can be read or written depending on whether *mode*is `'r'` (default) or `'w'`. The *buffering* argument has the same meaning as the corresponding argument to the built-in [`open()`](functions.xhtml#open "open") function. The returned file object reads or writes text strings rather than bytes.
The `close` method returns [`None`](constants.xhtml#None "None") if the subprocess exited successfully, or the subprocess's return code if there was an error. On POSIX systems, if the return code is positive it represents the return value of the process left-shifted by one byte. If the return code is negative, the process was terminated by the signal given by the negated value of the return code. (For example, the return value might be `- signal.SIGKILL` if the subprocess was killed.) On Windows systems, the return value contains the signed integer return code from the child process.
This is implemented using [`subprocess.Popen`](subprocess.xhtml#subprocess.Popen "subprocess.Popen"); see that class's documentation for more powerful ways to manage and communicate with subprocesses.
`os.``register_at_fork`(*\**, *before=None*, *after\_in\_parent=None*, *after\_in\_child=None*)Register callables to be executed when a new child process is forked using [`os.fork()`](#os.fork "os.fork") or similar process cloning APIs. The parameters are optional and keyword-only. Each specifies a different call point.
- *before* is a function called before forking a child process.
- *after\_in\_parent* is a function called from the parent process after forking a child process.
- *after\_in\_child* is a function called from the child process.
These calls are only made if control is expected to return to the Python interpreter. A typical [`subprocess`](subprocess.xhtml#module-subprocess "subprocess: Subprocess management.") launch will not trigger them as the child is not going to re-enter the interpreter.
Functions registered for execution before forking are called in reverse registration order. Functions registered for execution after forking (either in the parent or in the child) are called in registration order.
Note that `fork()` calls made by third-party C code may not call those functions, unless it explicitly calls [`PyOS_BeforeFork()`](../c-api/sys.xhtml#c.PyOS_BeforeFork "PyOS_BeforeFork"), [`PyOS_AfterFork_Parent()`](../c-api/sys.xhtml#c.PyOS_AfterFork_Parent "PyOS_AfterFork_Parent") and [`PyOS_AfterFork_Child()`](../c-api/sys.xhtml#c.PyOS_AfterFork_Child "PyOS_AfterFork_Child").
There is no way to unregister a function.
[可用性](intro.xhtml#availability): Unix。
3\.7 新版功能.
`os.``spawnl`(*mode*, *path*, *...*)`os.``spawnle`(*mode*, *path*, *...*, *env*)`os.``spawnlp`(*mode*, *file*, *...*)`os.``spawnlpe`(*mode*, *file*, *...*, *env*)`os.``spawnv`(*mode*, *path*, *args*)`os.``spawnve`(*mode*, *path*, *args*, *env*)`os.``spawnvp`(*mode*, *file*, *args*)`os.``spawnvpe`(*mode*, *file*, *args*, *env*)Execute the program *path* in a new process.
(Note that the [`subprocess`](subprocess.xhtml#module-subprocess "subprocess: Subprocess management.") module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the [Replacing Older Functions with the subprocess Module](subprocess.xhtml#subprocess-replacements) section.)
If *mode* is [`P_NOWAIT`](#os.P_NOWAIT "os.P_NOWAIT"), this function returns the process id of the new process; if *mode* is [`P_WAIT`](#os.P_WAIT "os.P_WAIT"), returns the process's exit code if it exits normally, or `-signal`, where *signal* is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with the [`waitpid()`](#os.waitpid "os.waitpid") function.
The "l" and "v" variants of the [`spawn*`](#os.spawnl "os.spawnl") functions differ in how command-line arguments are passed. The "l" variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the `spawnl*()` functions. The "v" variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the *args* parameter. In either case, the arguments to the child process must start with the name of the command being run.
The variants which include a second "p" near the end ([`spawnlp()`](#os.spawnlp "os.spawnlp"), [`spawnlpe()`](#os.spawnlpe "os.spawnlpe"), [`spawnvp()`](#os.spawnvp "os.spawnvp"), and [`spawnvpe()`](#os.spawnvpe "os.spawnvpe")) will use the `PATH` environment variable to locate the program *file*. When the environment is being replaced (using one of the [`spawn*e`](#os.spawnl "os.spawnl") variants, discussed in the next paragraph), the new environment is used as the source of the `PATH` variable. The other variants, [`spawnl()`](#os.spawnl "os.spawnl"), [`spawnle()`](#os.spawnle "os.spawnle"), [`spawnv()`](#os.spawnv "os.spawnv"), and [`spawnve()`](#os.spawnve "os.spawnve"), will not use the `PATH` variable to locate the executable; *path* must contain an appropriate absolute or relative path.
For [`spawnle()`](#os.spawnle "os.spawnle"), [`spawnlpe()`](#os.spawnlpe "os.spawnlpe"), [`spawnve()`](#os.spawnve "os.spawnve"), and [`spawnvpe()`](#os.spawnvpe "os.spawnvpe")(note that these all end in "e"), the *env* parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process' environment); the functions [`spawnl()`](#os.spawnl "os.spawnl"), [`spawnlp()`](#os.spawnlp "os.spawnlp"), [`spawnv()`](#os.spawnv "os.spawnv"), and [`spawnvp()`](#os.spawnvp "os.spawnvp") all cause the new process to inherit the environment of the current process. Note that keys and values in the *env* dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of `127`.
As an example, the following calls to [`spawnlp()`](#os.spawnlp "os.spawnlp") and [`spawnvpe()`](#os.spawnvpe "os.spawnvpe") are equivalent:
```
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
L = ['cp', 'index.html', '/dev/null']
os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
```
[Availability](intro.xhtml#availability): Unix, Windows. [`spawnlp()`](#os.spawnlp "os.spawnlp"), [`spawnlpe()`](#os.spawnlpe "os.spawnlpe"), [`spawnvp()`](#os.spawnvp "os.spawnvp")and [`spawnvpe()`](#os.spawnvpe "os.spawnvpe") are not available on Windows. [`spawnle()`](#os.spawnle "os.spawnle") and [`spawnve()`](#os.spawnve "os.spawnve") are not thread-safe on Windows; we advise you to use the [`subprocess`](subprocess.xhtml#module-subprocess "subprocess: Subprocess management.") module instead.
在 3.6 版更改: 接受一個 [類路徑對象](../glossary.xhtml#term-path-like-object)。
`os.``P_NOWAIT``os.``P_NOWAITO`Possible values for the *mode* parameter to the [`spawn*`](#os.spawnl "os.spawnl") family of functions. If either of these values is given, the `spawn*()` functions will return as soon as the new process has been created, with the process id as the return value.
[可用性](intro.xhtml#availability): Unix, Windows。
`os.``P_WAIT`Possible value for the *mode* parameter to the [`spawn*`](#os.spawnl "os.spawnl") family of functions. If this is given as *mode*, the `spawn*()` functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or `-signal` if a signal kills the process.
[可用性](intro.xhtml#availability): Unix, Windows。
`os.``P_DETACH``os.``P_OVERLAY`Possible values for the *mode* parameter to the [`spawn*`](#os.spawnl "os.spawnl") family of functions. These are less portable than those listed above. [`P_DETACH`](#os.P_DETACH "os.P_DETACH")is similar to [`P_NOWAIT`](#os.P_NOWAIT "os.P_NOWAIT"), but the new process is detached from the console of the calling process. If [`P_OVERLAY`](#os.P_OVERLAY "os.P_OVERLAY") is used, the current process will be replaced; the [`spawn*`](#os.spawnl "os.spawnl") function will not return.
[可用性](intro.xhtml#availability): Windows。
`os.``startfile`(*path*\[, *operation*\])Start a file with its associated application.
When *operation* is not specified or `'open'`, this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the **start** command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.
When another *operation* is given, it must be a "command verb" that specifies what should be done with the file. Common verbs documented by Microsoft are `'print'` and `'edit'` (to be used on files) as well as `'explore'` and `'find'` (to be used on directories).
[`startfile()`](#os.startfile "os.startfile") returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application's exit status. The *path* parameter is relative to the current directory. If you want to use an absolute path, make sure the first character is not a slash (`'/'`); the underlying Win32 `ShellExecute()` function doesn't work if it is. Use the [`os.path.normpath()`](os.path.xhtml#os.path.normpath "os.path.normpath") function to ensure that the path is properly encoded for Win32.
To reduce interpreter startup overhead, the Win32 `ShellExecute()`function is not resolved until this function is first called. If the function cannot be resolved, [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError") will be raised.
[可用性](intro.xhtml#availability): Windows。
`os.``system`(*command*)Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](sys.xhtml#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream.
On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](#os.wait "os.wait"). Note that POSIX does not specify the meaning of the return value of the C `system()` function, so the return value of the Python function is system-dependent.
On Windows, the return value is that returned by the system shell after running *command*. The shell is given by the Windows environment variable `COMSPEC`: it is usually **cmd.exe**, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation.
The [`subprocess`](subprocess.xhtml#module-subprocess "subprocess: Subprocess management.") module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the [Replacing Older Functions with the subprocess Module](subprocess.xhtml#subprocess-replacements) section in the [`subprocess`](subprocess.xhtml#module-subprocess "subprocess: Subprocess management.") documentation for some helpful recipes.
[可用性](intro.xhtml#availability): Unix, Windows。
`os.``times`()Returns the current global process times. The return value is an object with five attributes:
- `user` - user time
- [`system`](#os.system "os.system") - system time
- `children_user` - user time of all child processes
- `children_system` - system time of all child processes
- `elapsed` - elapsed real time since a fixed point in the past
For backwards compatibility, this object also behaves like a five-tuple containing `user`, [`system`](#os.system "os.system"), `children_user`, `children_system`, and `elapsed` in that order.
See the Unix manual page *times(2)* or the corresponding Windows Platform API documentation. On Windows, only `user` and [`system`](#os.system "os.system") are known; the other attributes are zero.
[可用性](intro.xhtml#availability): Unix, Windows。
在 3.3 版更改: 返回結果的類型由元組變成一個類似元組的對象,同時具有命名的屬性。
`os.``wait`()Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.
[可用性](intro.xhtml#availability): Unix。
`os.``waitid`(*idtype*, *id*, *options*)Wait for the completion of one or more child processes. *idtype* can be [`P_PID`](#os.P_PID "os.P_PID"), [`P_PGID`](#os.P_PGID "os.P_PGID") or [`P_ALL`](#os.P_ALL "os.P_ALL"). *id* specifies the pid to wait on. *options* is constructed from the ORing of one or more of [`WEXITED`](#os.WEXITED "os.WEXITED"), [`WSTOPPED`](#os.WSTOPPED "os.WSTOPPED") or [`WCONTINUED`](#os.WCONTINUED "os.WCONTINUED") and additionally may be ORed with [`WNOHANG`](#os.WNOHANG "os.WNOHANG") or [`WNOWAIT`](#os.WNOWAIT "os.WNOWAIT"). The return value is an object representing the data contained in the `siginfo_t` structure, namely: `si_pid`, `si_uid`, `si_signo`, `si_status`, `si_code` or `None` if [`WNOHANG`](#os.WNOHANG "os.WNOHANG") is specified and there are no children in a waitable state.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``P_PID``os.``P_PGID``os.``P_ALL`These are the possible values for *idtype* in [`waitid()`](#os.waitid "os.waitid"). They affect how *id* is interpreted.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``WEXITED``os.``WSTOPPED``os.``WNOWAIT`Flags that can be used in *options* in [`waitid()`](#os.waitid "os.waitid") that specify what child signal to wait for.
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``CLD_EXITED``os.``CLD_DUMPED``os.``CLD_TRAPPED``os.``CLD_CONTINUED`These are the possible values for `si_code` in the result returned by [`waitid()`](#os.waitid "os.waitid").
[可用性](intro.xhtml#availability): Unix。
3\.3 新版功能.
`os.``waitpid`(*pid*, *options*)The details of this function differ on Unix and Windows.
On Unix: Wait for completion of a child process given by process id *pid*, and return a tuple containing its process id and exit status indication (encoded as for [`wait()`](#os.wait "os.wait")). The semantics of the call are affected by the value of the integer *options*, which should be `0` for normal operation.
If *pid* is greater than `0`, [`waitpid()`](#os.waitpid "os.waitpid") requests status information for that specific process. If *pid* is `0`, the request is for the status of any child in the process group of the current process. If *pid* is `-1`, the request pertains to any child of the current process. If *pid* is less than `-1`, status is requested for any process in the process group `-pid` (the absolute value of *pid*).
An [`OSError`](exceptions.xhtml#OSError "OSError") is raised with the value of errno when the syscall returns -1.
On Windows: Wait for completion of a process given by process handle *pid*, and return a tuple containing *pid*, and its exit status shifted left by 8 bits (shifting makes cross-platform use of the function easier). A *pid* less than or equal to `0` has no special meaning on Windows, and raises an exception. The value of integer *options* has no effect. *pid* can refer to any process whose id is known, not necessarily a child process. The [`spawn*`](#os.spawnl "os.spawnl")functions called with [`P_NOWAIT`](#os.P_NOWAIT "os.P_NOWAIT") return suitable process handles.
在 3.5 版更改: 如果系統調用被中斷,但信號處理程序沒有觸發異常,此函數現在會重試系統調用,而不是觸發 [`InterruptedError`](exceptions.xhtml#InterruptedError "InterruptedError") 異常 (原因詳見 [**PEP 475**](https://www.python.org/dev/peps/pep-0475) \[https://www.python.org/dev/peps/pep-0475\])。
`os.``wait3`(*options*)Similar to [`waitpid()`](#os.waitpid "os.waitpid"), except no process id argument is given and a 3-element tuple containing the child's process id, exit status indication, and resource usage information is returned. Refer to [`resource`](resource.xhtml#module-resource "resource: An interface to provide resource usage information on the current process. (Unix)").[`getrusage()`](resource.xhtml#resource.getrusage "resource.getrusage") for details on resource usage information. The option argument is the same as that provided to [`waitpid()`](#os.waitpid "os.waitpid") and [`wait4()`](#os.wait4 "os.wait4").
[可用性](intro.xhtml#availability): Unix。
`os.``wait4`(*pid*, *options*)Similar to [`waitpid()`](#os.waitpid "os.waitpid"), except a 3-element tuple, containing the child's process id, exit status indication, and resource usage information is returned. Refer to [`resource`](resource.xhtml#module-resource "resource: An interface to provide resource usage information on the current process. (Unix)").[`getrusage()`](resource.xhtml#resource.getrusage "resource.getrusage") for details on resource usage information. The arguments to [`wait4()`](#os.wait4 "os.wait4") are the same as those provided to [`waitpid()`](#os.waitpid "os.waitpid").
[可用性](intro.xhtml#availability): Unix。
`os.``WNOHANG`The option for [`waitpid()`](#os.waitpid "os.waitpid") to return immediately if no child process status is available immediately. The function returns `(0, 0)` in this case.
[可用性](intro.xhtml#availability): Unix。
`os.``WCONTINUED`This option causes child processes to be reported if they have been continued from a job control stop since their status was last reported.
[可用性](intro.xhtml#availability): 部分 Unix 系統。
`os.``WUNTRACED`This option causes child processes to be reported if they have been stopped but their current state has not been reported since they were stopped.
[可用性](intro.xhtml#availability): Unix。
The following functions take a process status code as returned by [`system()`](#os.system "os.system"), [`wait()`](#os.wait "os.wait"), or [`waitpid()`](#os.waitpid "os.waitpid") as a parameter. They may be used to determine the disposition of a process.
`os.``WCOREDUMP`(*status*)Return `True` if a core dump was generated for the process, otherwise return `False`.
[可用性](intro.xhtml#availability): Unix。
`os.``WIFCONTINUED`(*status*)Return `True` if the process has been continued from a job control stop, otherwise return `False`.
[可用性](intro.xhtml#availability): Unix。
`os.``WIFSTOPPED`(*status*)Return `True` if the process has been stopped, otherwise return `False`.
[可用性](intro.xhtml#availability): Unix。
`os.``WIFSIGNALED`(*status*)Return `True` if the process exited due to a signal, otherwise return `False`.
[可用性](intro.xhtml#availability): Unix。
`os.``WIFEXITED`(*status*)Return `True` if the process exited using the *exit(2)* system call, otherwise return `False`.
[可用性](intro.xhtml#availability): Unix。
`os.``WEXITSTATUS`(*status*)If `WIFEXITED(status)` is true, return the integer parameter to the *exit(2)* system call. Otherwise, the return value is meaningless.
[可用性](intro.xhtml#availability): Unix。
`os.``WSTOPSIG`(*status*)Return the signal which caused the process to stop.
[可用性](intro.xhtml#availability): Unix。
`os.``WTERMSIG`(*status*)Return the signal which caused the process to exit.
[可用性](intro.xhtml#availability): Unix。
## Interface to the scheduler
These functions control how a process is allocated CPU time by the operating system. They are only available on some Unix platforms. For more detailed information, consult your Unix manpages.
3\.3 新版功能.
The following scheduling policies are exposed if they are supported by the operating system.
`os.``SCHED_OTHER`The default scheduling policy.
`os.``SCHED_BATCH`Scheduling policy for CPU-intensive processes that tries to preserve interactivity on the rest of the computer.
`os.``SCHED_IDLE`Scheduling policy for extremely low priority background tasks.
`os.``SCHED_SPORADIC`Scheduling policy for sporadic server programs.
`os.``SCHED_FIFO`A First In First Out scheduling policy.
`os.``SCHED_RR`A round-robin scheduling policy.
`os.``SCHED_RESET_ON_FORK`This flag can be OR'ed with any other scheduling policy. When a process with this flag set forks, its child's scheduling policy and priority are reset to the default.
*class* `os.``sched_param`(*sched\_priority*)This class represents tunable scheduling parameters used in [`sched_setparam()`](#os.sched_setparam "os.sched_setparam"), [`sched_setscheduler()`](#os.sched_setscheduler "os.sched_setscheduler"), and [`sched_getparam()`](#os.sched_getparam "os.sched_getparam"). It is immutable.
At the moment, there is only one possible parameter:
`sched_priority`The scheduling priority for a scheduling policy.
`os.``sched_get_priority_min`(*policy*)Get the minimum priority value for *policy*. *policy* is one of the scheduling policy constants above.
`os.``sched_get_priority_max`(*policy*)Get the maximum priority value for *policy*. *policy* is one of the scheduling policy constants above.
`os.``sched_setscheduler`(*pid*, *policy*, *param*)Set the scheduling policy for the process with PID *pid*. A *pid* of 0 means the calling process. *policy* is one of the scheduling policy constants above. *param* is a [`sched_param`](#os.sched_param "os.sched_param") instance.
`os.``sched_getscheduler`(*pid*)Return the scheduling policy for the process with PID *pid*. A *pid* of 0 means the calling process. The result is one of the scheduling policy constants above.
`os.``sched_setparam`(*pid*, *param*)Set a scheduling parameters for the process with PID *pid*. A *pid* of 0 means the calling process. *param* is a [`sched_param`](#os.sched_param "os.sched_param") instance.
`os.``sched_getparam`(*pid*)Return the scheduling parameters as a [`sched_param`](#os.sched_param "os.sched_param") instance for the process with PID *pid*. A *pid* of 0 means the calling process.
`os.``sched_rr_get_interval`(*pid*)Return the round-robin quantum in seconds for the process with PID *pid*. A *pid* of 0 means the calling process.
`os.``sched_yield`()Voluntarily relinquish the CPU.
`os.``sched_setaffinity`(*pid*, *mask*)Restrict the process with PID *pid* (or the current process if zero) to a set of CPUs. *mask* is an iterable of integers representing the set of CPUs to which the process should be restricted.
`os.``sched_getaffinity`(*pid*)Return the set of CPUs the process with PID *pid* (or the current process if zero) is restricted to.
## Miscellaneous System Information
`os.``confstr`(*name*)Return string-valued system configuration values. *name* specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the `confstr_names` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted.
If the configuration value specified by *name* isn't defined, `None` is returned.
If *name* is a string and is not known, [`ValueError`](exceptions.xhtml#ValueError "ValueError") is raised. If a specific value for *name* is not supported by the host system, even if it is included in `confstr_names`, an [`OSError`](exceptions.xhtml#OSError "OSError") is raised with [`errno.EINVAL`](errno.xhtml#errno.EINVAL "errno.EINVAL") for the error number.
[可用性](intro.xhtml#availability): Unix。
`os.``confstr_names`Dictionary mapping names accepted by [`confstr()`](#os.confstr "os.confstr") to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.
[可用性](intro.xhtml#availability): Unix。
`os.``cpu_count`()Return the number of CPUs in the system. Returns `None` if undetermined.
該數量不同于當前進程可以使用的CPU數量。可用的CPU數量可以由 `len(os.sched_getaffinity(0))` 方法獲得。
3\.4 新版功能.
`os.``getloadavg`()Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises [`OSError`](exceptions.xhtml#OSError "OSError") if the load average was unobtainable.
[可用性](intro.xhtml#availability): Unix。
`os.``sysconf`(*name*)Return integer-valued system configuration values. If the configuration value specified by *name* isn't defined, `-1` is returned. The comments regarding the *name* parameter for [`confstr()`](#os.confstr "os.confstr") apply here as well; the dictionary that provides information on the known names is given by `sysconf_names`.
[可用性](intro.xhtml#availability): Unix。
`os.``sysconf_names`Dictionary mapping names accepted by [`sysconf()`](#os.sysconf "os.sysconf") to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.
[可用性](intro.xhtml#availability): Unix。
The following data values are used to support path manipulation operations. These are defined for all platforms.
Higher-level operations on pathnames are defined in the [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.") module.
`os.``curdir`The constant string used by the operating system to refer to the current directory. This is `'.'` for Windows and POSIX. Also available via [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.").
`os.``pardir`The constant string used by the operating system to refer to the parent directory. This is `'..'` for Windows and POSIX. Also available via [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.").
`os.``sep`The character used by the operating system to separate pathname components. This is `'/'` for POSIX and `'\\'` for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames --- use [`os.path.split()`](os.path.xhtml#os.path.split "os.path.split") and [`os.path.join()`](os.path.xhtml#os.path.join "os.path.join") --- but it is occasionally useful. Also available via [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.").
`os.``altsep`An alternative character used by the operating system to separate pathname components, or `None` if only one separator character exists. This is set to `'/'` on Windows systems where `sep` is a backslash. Also available via [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.").
`os.``extsep`The character which separates the base filename from the extension; for example, the `'.'` in `os.py`. Also available via [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.").
`os.``pathsep`The character conventionally used by the operating system to separate search path components (as in `PATH`), such as `':'` for POSIX or `';'` for Windows. Also available via [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.").
`os.``defpath`The default search path used by [`exec*p*`](#os.execl "os.execl") and [`spawn*p*`](#os.spawnl "os.spawnl") if the environment doesn't have a `'PATH'`key. Also available via [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.").
`os.``linesep`The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as `'\n'` for POSIX, or multiple characters, for example, `'\r\n'` for Windows. Do not use *os.linesep* as a line terminator when writing files opened in text mode (the default); use a single `'\n'` instead, on all platforms.
`os.``devnull`The file path of the null device. For example: `'/dev/null'` for POSIX, `'nul'` for Windows. Also available via [`os.path`](os.path.xhtml#module-os.path "os.path: Operations on pathnames.").
`os.``RTLD_LAZY``os.``RTLD_NOW``os.``RTLD_GLOBAL``os.``RTLD_LOCAL``os.``RTLD_NODELETE``os.``RTLD_NOLOAD``os.``RTLD_DEEPBIND`Flags for use with the [`setdlopenflags()`](sys.xhtml#sys.setdlopenflags "sys.setdlopenflags") and [`getdlopenflags()`](sys.xhtml#sys.getdlopenflags "sys.getdlopenflags") functions. See the Unix manual page *dlopen(3)* for what the different flags mean.
3\.3 新版功能.
## Random numbers
`os.``getrandom`(*size*, *flags=0*)Get up to *size* random bytes. The function can return less bytes than requested.
These bytes can be used to seed user-space random number generators or for cryptographic purposes.
`getrandom()` relies on entropy gathered from device drivers and other sources of environmental noise. Unnecessarily reading large quantities of data will have a negative impact on other users of the `/dev/random` and `/dev/urandom` devices.
The flags argument is a bit mask that can contain zero or more of the following values ORed together: [`os.GRND_RANDOM`](#os.GRND_RANDOM "os.GRND_RANDOM") and [`GRND_NONBLOCK`](#os.GRND_NONBLOCK "os.GRND_NONBLOCK").
See also the [Linux getrandom() manual page](http://man7.org/linux/man-pages/man2/getrandom.2.html) \[http://man7.org/linux/man-pages/man2/getrandom.2.html\].
[Availability](intro.xhtml#availability): Linux 3.17 and newer.
3\.6 新版功能.
`os.``urandom`(*size*)Return a string of *size* random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.
On Linux, if the `getrandom()` syscall is available, it is used in blocking mode: block until the system urandom entropy pool is initialized (128 bits of entropy are collected by the kernel). See the [**PEP 524**](https://www.python.org/dev/peps/pep-0524) \[https://www.python.org/dev/peps/pep-0524\] for the rationale. On Linux, the [`getrandom()`](#os.getrandom "os.getrandom") function can be used to get random bytes in non-blocking mode (using the [`GRND_NONBLOCK`](#os.GRND_NONBLOCK "os.GRND_NONBLOCK") flag) or to poll until the system urandom entropy pool is initialized.
On a Unix-like system, random bytes are read from the `/dev/urandom`device. If the `/dev/urandom` device is not available or not readable, the [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError") exception is raised.
On Windows, it will use `CryptGenRandom()`.
參見
The [`secrets`](secrets.xhtml#module-secrets "secrets: Generate secure random numbers for managing secrets.") module provides higher level functions. For an easy-to-use interface to the random number generator provided by your platform, please see [`random.SystemRandom`](random.xhtml#random.SystemRandom "random.SystemRandom").
在 3.6.0 版更改: On Linux, `getrandom()` is now used in blocking mode to increase the security.
在 3.5.2 版更改: On Linux, if the `getrandom()` syscall blocks (the urandom entropy pool is not initialized yet), fall back on reading `/dev/urandom`.
在 3.5 版更改: On Linux 3.17 and newer, the `getrandom()` syscall is now used when available. On OpenBSD 5.6 and newer, the C `getentropy()`function is now used. These functions avoid the usage of an internal file descriptor.
`os.``GRND_NONBLOCK`By default, when reading from `/dev/random`, [`getrandom()`](#os.getrandom "os.getrandom") blocks if no random bytes are available, and when reading from `/dev/urandom`, it blocks if the entropy pool has not yet been initialized.
If the [`GRND_NONBLOCK`](#os.GRND_NONBLOCK "os.GRND_NONBLOCK") flag is set, then [`getrandom()`](#os.getrandom "os.getrandom") does not block in these cases, but instead immediately raises [`BlockingIOError`](exceptions.xhtml#BlockingIOError "BlockingIOError").
3\.6 新版功能.
`os.``GRND_RANDOM`If this bit is set, then random bytes are drawn from the `/dev/random` pool instead of the `/dev/urandom` pool.
3\.6 新版功能.
### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](io.xhtml "io --- 處理流的核心工具") |
- [上一頁](allos.xhtml "通用操作系統服務") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 標準庫](index.xhtml) ?
- [通用操作系統服務](allos.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