os --- 各種作業系統介面

原始碼:Lib/os.py


該模組提供了一種便利的方式來操作與作業系統相關的功能。如果你想讀取或寫入檔案,請參閱 open() ,如果你想操作檔案路徑,請參閱 os.path 模組,如果你想透過命令列查看所有檔案中的所有內容,請查看 fileinput 模組。要建立臨時檔案和目錄,請參閱 tempfile 模組,要操作高級檔案和目錄,請參閱 shutil 模組。

關於這些功能的可用性說明:

  • Python 所有內建作業系統相關的模組設計是這樣:只要有相同的函式可使用,就會使用相同的介面 (interface)。舉例來說,os.stat(path) 函式會以相同格式回傳關於 path 的統計資訊(這剛好來自於 POSIX 的介面。)。

  • 對於特定的作業系統獨有的擴充功能也可以透過 os 取得,但使用它們的時候對於可移植性無疑會是個問題。

  • 所有接受檔案路徑和檔案名稱的函式皆接受位元組 (bytes) 和字串物件 (string objects),且如果回傳檔案路徑或檔案名稱,則會產出相同型別的物件。

  • 在 VxWorks, 不支援 os.popen、os.fork、os.execv 和 os.spawn*p*。

  • 在 WebAssembly 平台和 Android 與 iOS 上,大部分 os 模組無法使用或行為不同。與行程 (process)(例如 fork()execve())與資源(例如 nice())相關的 API 不可使用。其他諸如 getuid()getpid() 的相關 API 是 emulated 或 stubs。WebAssembly 平台也缺少訊號相關支援(例如 kill()wait())。

備註

在檔案名稱和路徑找不到或無效的時候,或引數型別正確但作業系統不接受的時候,在此模組中的所有的函式都會引發 OSError(或其子類別)。

exception os.error

內建例外 OSError 的別名。

os.name

The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'.

也參考

sys.platform has a finer granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system's identity.

File Names, Command Line Arguments, and Environment Variables

In Python, file names, command line arguments, and environment variables are represented using the string type. On some systems, decoding these strings to and from bytes is necessary before passing them to the operating system. Python uses the filesystem encoding and error handler to perform this conversion (see sys.getfilesystemencoding()).

The filesystem encoding and error handler are configured at Python startup by the PyConfig_Read() function: see filesystem_encoding and filesystem_errors members of PyConfig.

在 3.1 版的變更: On some systems, conversion using the file system encoding may fail. In this case, Python uses the surrogateescape encoding error handler, which means that undecodable bytes are replaced by a Unicode character U+DCxx on decoding, and these are again translated to the original byte on encoding.

The file system encoding must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions can raise UnicodeError.

另請參閱 locale encoding

Python UTF-8 模式

在 3.7 版被加入: 更多資訊請見 PEP 540

Python 在 UTF-8 模式下會忽略 locale encoding 並且強制使用 UTF-8 去編碼:

請注意,在 UTF-8 模式中,標準的串流設定會被 PYTHONIOENCODING 覆蓋(如同在預設在地化覺察 模式一樣)。

As a consequence of the changes in those lower level APIs, other higher level APIs also exhibit different default behaviours:

  • 命令列引數、環境變數及檔案名稱會以 UTF-8 編碼形式來被解碼成文字。

  • os.fsdecode()os.fsencode() 使用 UTF-8 編碼。