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(或其子類別)。
- os.name¶
The name of the operating system dependent module imported. The following names have currently been registered:
'posix','nt','java'.也參考
sys.platformhas a finer granularity.os.uname()gives system-dependent version information.The
platformmodule 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 去編碼:
Use UTF-8 as the filesystem encoding.
sys.getfilesystemencoding()回傳'utf-8'。locale.getpreferredencoding()回傳'utf-8'(do_setlocale 引數並無任何效果)。sys.stdin,sys.stdout, andsys.stderrall use UTF-8 as their text encoding, with thesurrogateescapeerror handler being enabled forsys.stdinandsys.stdout(sys.stderrcontinues to usebackslashreplaceas it does in the default locale-aware mode)在 Unix 中,
os.device_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 編碼。open(),io.open(), andcodecs.open()use the UTF-8 encoding by default. However, they still use the strict error handler by default so that attempting to open a binary file in text mode is likely to raise an exception rather than producing nonsense data.
The Python UTF-8 Mode is enabled if the LC_CTYPE locale is
C or POSIX at Python startup (see the PyConfig_Read()
function).
It can be enabled or disabled using the -X utf8 command line
option and the PYTHONUTF8 environment variable.
If the PYTHONUTF8 environment variable is not set at all, then the
interpreter defaults to using the current locale settings, unless the current
locale is identified as a legacy ASCII-based locale (as described for
PYTHONCOERCECLOCALE), and locale coercion is either disabled or
fails. In such legacy locales, the interpreter will default to enabling UTF-8
mode unless explicitly instructed not to do so.
The Python UTF-8 Mode can only be enabled at the Python startup. Its value
can be read from sys.flags.utf8_mode.
See also the UTF-8 mode on Windows and the filesystem encoding and error handler.
也參考
- PEP 686
Python 3.15 預設使用 Python UTF-8 模式
行程參數¶
These functions and data items provide information and operate on the current process and user.
- os.ctermid()¶
Return the filename corresponding to the controlling terminal of the process.
可用性: Unix, not WASI.
- os.environ¶
A mapping object where keys and values are strings that represent the process environment. For example,
environ['HOME']is the pathname of your home directory (on some platforms), and is equivalent togetenv("HOME")in C.This mapping is captured the first time the
osmodule is imported, typically during Python startup as part of processingsite.py. Changes to the environment made after this time are not reflected inos.environ, except for changes made by modifyingos.environdirectly.This mapping may be used to modify the environment as well as query the environment.
putenv()will be called automatically when the mapping is modified.On Unix, keys and values use
sys.getfilesystemencoding()and'surrogateescape'error handler. Useenvironbif you would like to use a different encoding.On Windows, the keys are converted to uppercase. This also applies when getting, setting, or deleting an item. For example,
environ['monty'] = 'python'maps the key'MONTY'to the value'python'.備註
呼叫
putenv()並不會改變os.environ,所以建議直接修改os.environ。備註
On some platforms, including FreeBSD and macOS, setting
environmay cause memory leaks. Refer to the system documentation forputenv().You can delete items in this mapping to unset environment variables.
unsetenv()will be called automatically when an item is deleted fromos.environ, and when one of thepop()orclear()methods is called.也參考
在 3.9 版的變更: Updated to support PEP 584's merge (
|) and update (|=) operators.
- os.environb¶
Bytes version of
environ: a mapping object where both keys and values arebytesobjects representing the process environment.environandenvironbare synchronized (modifyingenvironbupdatesenviron, and vice versa).environbis only available ifsupports_bytes_environisTrue.在 3.2 版被加入.
在 3.9 版的變更: Updated to support PEP 584's merge (
|) and update (|=) operators.
- os.reload_environ()¶
The
os.environandos.environbmappings are a cache of environment variables at the time that Python started. As such, changes to the current process environment are not reflected if made outside Python, or byos.putenv()oros.unsetenv(). Useos.reload_environ()to updateos.environandos.environbwith any such changes to the current process environment.警告
This function is not thread-safe. Calling it while the environment is being modified in another thread is an undefined behavior. Reading from
os.environoros.environb, or callingos.getenv()while reloading, may return an empty result.在 3.14 版被加入.
- os.chdir(path)
- os.fchdir(fd)
- os.getcwd()
These functions are described in Files and Directories.
- os.fsencode(filename)¶
Encode path-like filename to the filesystem encoding and error handler; return
bytesunchanged.fsdecode()是反函式。在 3.2 版被加入.
在 3.6 版的變更: Support added to accept objects implementing the
os.PathLikeinterface.
- os.fsdecode(filename)¶
Decode the path-like filename from the filesystem encoding and error handler; return
strunchanged.fsencode()是反函式。在 3.2 版被加入.
在 3.6 版的變更: Support added to accept objects implementing the
os.PathLikeinterface.
- os.fspath(path)¶
Return the file system representation of the path.
If
strorbytesis passed in, it is returned unchanged. Otherwise__fspath__()is called and its value is returned as long as it is astrorbytesobject. In all other cases,TypeErroris raised.在 3.6 版被加入.
- class os.PathLike¶
An abstract base class for objects representing a file system path, e.g.
pathlib.PurePath.在 3.6 版被加入.
- os.getenv(key, default=None)¶
Return the value of the environment variable key as a string if it exists, or default if it doesn't. key is a string. Note that since
getenv()usesos.environ, the mapping ofgetenv()is similarly also captured on import, and the function may not reflect future environment changes.On Unix, keys and values are decoded with
sys.getfilesystemencoding()and'surrogateescape'error handler. Useos.getenvb()if you would like to use a different encoding.可用性: Unix, Windows.
- os.getenvb