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 編碼。

  • open(), io.open(), and codecs.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 to getenv("HOME") in C.

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

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. Use environb if 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 environ may cause memory leaks. Refer to the system documentation for putenv().

You can delete items in this mapping to unset environment variables. unsetenv() will be called automatically when an item is deleted from os.environ, and when one of the pop() or clear() methods is called.

也參考

os.reload_environ() 函式。

在 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 are bytes objects representing the process environment. environ and environb are synchronized (modifying environb updates environ, and vice versa).

environb is only available if supports_bytes_environ is True.

在 3.2 版被加入.

在 3.9 版的變更: Updated to support PEP 584's merge (|) and update (|=) operators.

os.reload_environ()

The os.environ and os.environb mappings 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 by os.putenv() or os.unsetenv(). Use os.reload_environ() to update os.environ and os.environb with 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.environ or os.environb, or calling os.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 bytes unchanged.

fsdecode() 是反函式。

在 3.2 版被加入.

在 3.6 版的變更: Support added to accept objects implementing the os.PathLike interface.

os.fsdecode(filename)

Decode the path-like filename from the filesystem encoding and error handler; return str unchanged.

fsencode() 是反函式。

在 3.2 版被加入.

在 3.6 版的變更: Support added to accept objects implementing the os.PathLike interface.

os.fspath(path)

Return the file system representation of the path.

If str or bytes is passed in, it is returned unchanged. Otherwise __fspath__() is called and its value is returned as long as it is a str or bytes object. In all other cases, TypeError is raised.

在 3.6 版被加入.

class os.PathLike

An abstract base class for objects representing a file system path, e.g. pathlib.PurePath.

在 3.6 版被加入.

abstractmethod __fspath__()

Return the file system path representation of the object.

The method should only return a str or bytes object, with the preference being for str.

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() uses os.environ, the mapping of getenv() 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. Use os.getenvb() if you would like to use a different encoding.

可用性: Unix, Windows.

os.getenvb(key, default=None)

Return the value of the environment variable key as bytes if it exists, or default if it doesn't. key must be bytes. Note that since getenvb() uses os.environb, the mapping of getenvb() is similarly also captured on import, and the function may not reflect future environment changes.

getenvb() is only available if supports_bytes_environ is True.

可用性: Unix.

在 3.2 版被加入.

os.get_exec_path(env=None)

Returns the list of directories that will be searched for a named executable, similar to a shell, when launching a process. env, when specified, should be an environment variable dictionary to lookup the PATH in. By default, when env is None, environ is used.

在 3.2 版被加入.

os.getegid()

Return the effective group id of the current process. This corresponds to the "set id" bit on the file being executed in the current process.

可用性: Unix, not WASI.

os.geteuid()

Return the current process's effective user id.

可用性: Unix, not WASI.

os.getgid()

Return the real group id of the current process.

可用性: Unix.

The function is a stub on WASI, see WebAssembly 平台 for more information.

os.getgrouplist(user, group, /)

Return list of group ids that user belongs to. If group is not in the list, it is included; typically, group is specified as the group ID field from the password record for user, because that group ID will otherwise be potentially omitted.

可用性: Unix, not WASI.

在 3.3 版被加入.

os.getgroups()

Return list of supplemental group ids associated with the current process.

可用性: Unix, not WASI.

備註

On macOS, getgroups() behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of 10.5 or earlier, getgroups() returns the list of effective group ids associated with the current user process; this list is limited to a system-defined number of entries, typically 16, and may be modified by calls to setgroups() if suitably privileged. If built with a deployment target greater than 10.5, getgroups() returns the current group access list for the user associated with the effective user id of the process; the group access list may change over the lifetime of the process, it is not affected by calls to setgroups(), and its length is not limited to 16. The deployment target value, MACOSX_DEPLOYMENT_TARGET, can be obtained with sysconfig.get_config_var().

os.getlogin()

Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use getpass.getuser() since the latter checks the environment variables LOGNAME or USERNAME to find out who the user is, and falls back to pwd.getpwuid(os.getuid())[0] to get the login name of the current real user id.

可用性: Unix, Windows, not WASI.

os.getpgid(pid)

Return the process group id of the process with process id pid. If pid is 0, the process group id of the current process is returned.

可用性: Unix, not WASI.

os.getpgrp()

Return the id of the current process group.

可用性: Unix, not WASI.

os.getpid()

Return the current process id.

The function is a stub on WASI, see WebAssembly 平台 for more information.

os.getppid()

Return the parent's process id. When the parent process has exited, on Unix the id returned is the one of the init process (1), on Windows it is still the same id, which may be already reused by another process.

可用性: Unix, Windows, not WASI.

在 3.2 版的變更: 新增對 Windows 的支援。

os.getpriority(which, who)

Get program scheduling priority. The value which is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process.

可用性: Unix, not WASI.

在 3.3 版被加入.

os.PRIO_PROCESS
os.PRIO_PGRP
os.PRIO_USER

Parameters for the getpriority() and setpriority() functions.

可用性: Unix, not WASI.

在 3.3 版被加入.

os.PRIO_DARWIN_THREAD
os.PRIO_DARWIN_PROCESS
os.PRIO_DARWIN_BG
os.PRIO_DARWIN_NONUI

Parameters for the getpriority() and setpriority() functions.

可用性: macOS

在 3.12 版被加入.

os.getresuid()

Return a tuple (ruid, euid, suid) denoting the current process's real, effective, and saved user ids.

可用性: Unix, not WASI.

在 3.2 版被加入.

os.getresgid()

Return a tuple (rgid, egid, sgid) denoting the current process's real, effective, and saved group ids.

可用性: Unix, not WASI.

在 3.2 版被加入.

os.getuid()

Return the current process's real user id.

可用性: Unix.

The function is a stub on WASI, see WebAssembly 平台 for more information.

os.initgroups(username, gid, /)

Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified group id.

可用性: Unix, not WASI, not Android.

在 3.2 版被加入.

os.putenv(key, value, /)

Set the environment variable named key to the string value. Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv().

Assignments to items in os.environ are automatically translated into corresponding calls to putenv(); however, calls to putenv() don't update os.environ, so it is actually preferable to assign to items of os.environ. This also applies to getenv() and getenvb(), which respectively use os.environ and os.environb in their implementations.

也請見 os.reload_environ() 函式。

備註

On some platforms, including FreeBSD and macOS, setting environ may cause memory leaks. Refer to the system documentation for putenv().

引發一個附帶引數 keyvalue稽核事件 os.putenv

在 3.9 版的變更: 此函式現在都會是可用的。

os.setegid(egid, /)

Set the current process's effective group id.

可用性: Unix, not WASI, not Android.

os.seteuid(euid, /)

Set the current process's effective user id.

可用性: Unix, not WASI, not Android.

os.setgid(gid, /)

Set the current process' group id.

可用性: Unix, not WASI, not Android.

os.setgroups(groups, /)

Set the list of supplemental group ids associated with the current process to groups. groups must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser.

可用性: Unix, not WASI.

備註

On macOS, the length of groups may not exceed the system-defined maximum number of effective group ids, typically 16. See the documentation for getgroups() for cases where it may not return the same group list set by calling setgroups().

os.setns(fd, nstype=0)

Reassociate the current thread with a Linux namespace. See the setns(2) and namespaces(7) man pages for more details.

If fd refers to a /proc/pid/ns/ link, setns() reassociates the calling thread with the namespace associated with that link, and nstype may be set to one of the CLONE_NEW* constants to impose constraints on the operation (0 means no constraints).

Since Linux 5.8, fd may refer to a PID file descriptor obtained from pidfd_open(). In this case, setns() reassociates the calling thread into one or more of the same namespaces as the thread referred to by fd. This is subject to any constraints imposed by nstype, which is a bit mask combining one or more of the CLONE_NEW* constants, e.g. setns(fd, os.CLONE_NEWUTS | os.CLONE_NEWPID). The caller's memberships in unspecified namespaces are left unchanged.

fd can be any object with a fileno() method, or a raw file descriptor.

This example reassociates the thread with the init process's network namespace:

fd = os.open("/proc/1/ns/net", os.O_RDONLY)
os.setns(fd, os.CLONE_NEWNET)
os.close(fd)

可用性: Linux >= 3.0 with glibc >= 2.14.

在 3.12 版被加入.

也參考

unshare() 函式。

os.setpgrp()

Call the system call setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics.

可用性: Unix, not WASI.

os.setpgid(pid, pgrp, /)

Call the system call setpgid() to set the process group id of the process with id pid to the process group with id pgrp. See the Unix manual for the semantics.

可用性: Unix, not WASI.

os.setpriority(which, who, priority)

Set program scheduling priority. The value which is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process. priority is a value in the range -20 to 19. The default priority is 0; lower priorities cause more favorable scheduling.

可用性: Unix, not WASI.

在 3.3 版被加入.

os.setregid(rgid, egid, /)

Set the current process's real and effective group ids.

可用性: Unix, not WASI, not Android.

os.setresgid(rgid, egid, sgid, /)

Set the current process's real, effective, and saved group ids.

可用性: Unix, not WASI, not Android.

在 3.2 版被加入.

os.setresuid(ruid, euid, suid, /)

Set the current process's real, effective, and saved user ids.

可用性: Unix, not WASI, not Android.

在 3.2 版被加入.

os.setreuid(ruid, euid, /)

Set the current process's real and effective user ids.

可用性: Unix, not WASI, not Android.

os.getsid(pid, /)

Call the system call getsid(). See the Unix manual for the semantics.

可用性: Unix, not WASI.

os.setsid()

Call the system call setsid(). See the Unix manual for the semantics.

可用性: Unix, not WASI.

os.setuid(uid, /)

Set the current process's user id.

可用性: Unix, not WASI, not Android.

os.strerror(code, /)

Return the error message corresponding to the error code in code. On platforms where strerror() returns NULL when given an unknown error number, ValueError is raised.

os.supports_bytes_environ

True if the native OS type of the environment is bytes (eg. False on Windows).

在 3.2 版被加入.

os.umask(mask, /)

Set the current numeric umask and return the previous umask.

The function is a stub on WASI, see WebAssembly 平台 for more information.

os.uname()

Returns information identifying the current operating system. The return value is an object with five attributes:

  • sysname - 作業系統名稱

  • nodename - name of machine on network (implementation-defined)

  • release - operating system release

  • version - 作業系統版本

  • machine - hardware identifier

For backwards compatibility, this object is also iterable, behaving like a five-tuple containing sysname, nodename, release, version, and machine in that order.

Some systems truncate nodename to 8 characters or to the leading component; a better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()).

On macOS, iOS and Android, this returns the kernel name and version (i.e., 'Darwin' on macOS and iOS; 'Linux' on Android). platform.uname() can be used to get the user-facing operating system name and version on iOS and Android.

可用性: Unix.

在 3.3 版的變更: Return type changed from a tuple to a tuple-like object with named attributes.

os.unsetenv(key, /)

Unset (delete) the environment variable named key. Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv().

Deletion of items in os.environ is automatically translated into a corresponding call to unsetenv(); however, calls to unsetenv() don't update os.environ, so it is actually preferable to delete items of os.environ.

也請見 os.reload_environ() 函式。

引發一個附帶引數 key稽核事件 os.unsetenv

在 3.9 版的變更: The function is now always available and is also available on Windows.

os.unshare(flags)

Disassociate parts of the process execution context, and move them into a newly created namespace. See the unshare(2) man page for more details. The flags argument is a bit mask, combining zero or more of the CLONE_* constants, that specifies which parts of the execution context should be unshared from their existing associations and moved to a new namespace. If the flags argument is 0, no changes are made to the calling process's execution context.

可用性: Linux >= 2.6.16.

在 3.12 版被加入.

也參考

setns() 函式。

Flags to the unshare() function, if the implementation supports them. See unshare(2) in the Linux manual for their exact effect and availability.

os.CLONE_FILES
os.CLONE_FS
os.CLONE_NEWCGROUP
os.CLONE_NEWIPC
os.CLONE_NEWNET
os.CLONE_NEWNS
os.CLONE_NEWPID
os.CLONE_NEWTIME
os.CLONE_NEWUSER
os.CLONE_NEWUTS
os.CLONE_SIGHAND
os.CLONE_SYSVSEM
os.CLONE_THREAD
os.CLONE_VM

File Object Creation

These functions create new file objects. (See also open() for opening file descriptors.)

os.fdopen(fd, *args, **kwargs)

Return an open file object connected to the file descriptor fd. This is an alias of the open() built-in function and accepts the same arguments. The only difference is that the first argument of fdopen() must always be an integer.

File Descriptor Operations

These functions operate on I/O streams referenced using file descriptors.

File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. The name "file descriptor" is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors.

The fileno() method can be used to obtain the file descriptor associated with a file object when required. Note that using the file descriptor directly will bypass the file object methods, ignoring aspects such as internal buffering of data.

os.close(fd)

Close file descriptor fd.

備註

This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe(). To close a "file object" returned by the built-in function open() or by popen() or fdopen(), use its close() method.

os.closerange(fd_low, fd_high, /)

Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. Equivalent to (but much faster than):

for fd in range(fd_low, fd_high):
    try:
        os.close(fd)
    except OSError:
        pass
os.copy_file_range(src, dst, count, offset_src=None, offset_dst=None)

Copy count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst. If offset_src is None, then src is read from the current position; respectively for offset_dst.

In Linux kernel older than 5.3, the files pointed to by src and dst must reside in the same filesystem, otherwise an OSError is raised with errno set to errno.EXDEV.

This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel. Additionally, some filesystems could implement extra optimizations, such as the use of reflinks (i.e., two or more inodes that share pointers to the same copy-on-write disk blocks; supported file systems include btrfs and XFS) and server-side copy (in the case of NFS).

The function copies bytes between two file descriptors. Text options, like the encoding and the line ending, are ignored.

The return value is the amount of bytes copied. This could be less than the amount requested.

備註

On Linux, os.copy_file_range() should not be used for copying a range of a pseudo file from a special filesystem like procfs and sysfs. It will always copy no bytes and return 0 as if the file was empty because of a known Linux kernel issue.

可用性: Linux >= 4.5 with glibc >= 2.27.

在 3.8 版被加入.

os.device_encoding(fd)

Return a string describing the encoding of the device associated with fd if it is connected to a terminal; else return None.

On Unix, if the Python UTF-8 Mode is enabled, return 'UTF-8' rather than the device encoding.

在 3.10 版的變更: On Unix, the function now implements the Python UTF-8 Mode.

os.dup(fd, /)

Return a duplicate of file descriptor fd. The new file descriptor is non-inheritable.

On Windows, when duplicating a standard stream (0: stdin, 1: stdout, 2: stderr), the new file descriptor is inheritable.

可用性: not WASI.

在 3.4 版的變更: The new file descriptor is now non-inheritable.

os.dup2(fd, fd2, inheritable=True)

Duplicate file descriptor fd to fd2, closing the latter first if necessary. Return fd2. The new file descriptor is inheritable by default or non-inheritable if inheritable is False.

可用性: not WASI.

在 3.4 版的變更: 新增可選用的參數 inheritable

在 3.7 版的變更: Return fd2 on success. Previously, None was always returned.

os.fchmod(fd, mode)

Change the mode of the file given by fd to the numeric mode. See the docs for chmod() for possible values of mode. As of Python 3.3, this is equivalent to os.chmod(fd, mode).

引發一個附帶引數 pathmodedir_fd稽核事件 os.chmod

可用性: Unix, Windows.

The function is limited on WASI, see WebAssembly 平台 for more information.

在 3.13 版的變更: 新增對 Windows 的支援。

os.fchown(fd, uid, gid)

Change the owner and group id of the file given by fd to the numeric uid and gid. To leave one of the ids unchanged, set it to -1. See chown(). As of Python 3.3, this is equivalent to os.chown(fd, uid, gid).

引發一個附帶引數 pathuidgiddir_fd稽核事件 os.chown

可用性: Unix.

The function is limited on WASI, see WebAssembly 平台 for more information.

os.fdatasync(fd)

Force write of file with filedescriptor fd to disk. Does not force update of metadata.

可用性: Unix.

備註

This function is not available on 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 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 is raised with errno.EINVAL for the error number.

As of Python 3.3, this is equivalent to os.pathconf(fd, name).

可用性: Unix.

os.fstat(fd)

Get the status of the file descriptor fd. Return a stat_result object.

As of Python 3.3, this is equivalent to os.stat(fd).

也參考

The stat() function.

os.fstatvfs(fd, /)

Return information about the filesystem containing the file associated with file descriptor fd, like statvfs(). As of Python 3.3, this is equivalent to os.statvfs(fd).

可用性: 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 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.

可用性: 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).

引發一個附帶引數 fdlength稽核事件 os.truncate

可用性: Unix, Windows.

在 3.5 版的變更: 新增對 Windows 的支援

os.get_blocking(fd, /)

Get the blocking mode of the file descriptor: False if the O_NONBLOCK flag is set, True if the flag is cleared.

另請參閱 set_blocking()socket.socket.setblocking()

可用性: Unix, Windows.

The function is limited on WASI, see WebAssembly 平台 for more information.

On Windows, this function is limited to pipes.

在 3.5 版被加入.

在 3.12 版的變更: 新增對 Windows 上的 pipe 支援。

os.grantpt(fd, /)

Grant access to the slave pseudo-terminal device associated with the master pseudo-terminal device to which the file descriptor fd refers. The file descriptor fd is not closed upon failure.

Calls the C standard library function grantpt().

可用性: Unix, not WASI.

在 3.13 版被加入.

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, F_TLOCK, F_ULOCK or F_TEST. len specifies the section of the file to lock.

引發一個附帶引數 fdcmdlen稽核事件 os.lockf

可用性: Unix.

在 3.3 版被加入.

os.F_LOCK
os.F_TLOCK