os
一般操作系统服务
源代码: Lib/os.py
此模块提供使用操作系统从属功能的可移植方式。若仅仅想要读取或写入文件,见 open() ,若想要操纵路径,见 os.path 模块,若想要在命令行中读取所有文件中的所有行,见 fileinput 模块。对于创建临时文件和目录,见 tempfile 模块,对于高级文件和目录处理,见 shutil 模块。
open()
os.path
fileinput
tempfile
shutil
有关这些函数的可用性的注意事项:
Python 所有内置操作系统依赖模块的设计是这样的,只要相同功能可用,就使用相同接口;例如,函数 os.stat(path) 返回的统计信息关于 path 按相同格式 (恰好发源于 POSIX 接口)。
os.stat(path)
特定操作系统的特有扩展也可用透过 os 模块,但使用它们当然威及可移植性。
所有接受路径或文件名两者的函数都接受字节和字符串对象,且结果为相同类型对象若返回路径或文件名。
VxWorks 不支持 os.popen、os.fork、os.execv 及 os.spawn*p*。
在 WebAssembly 平台 wasm32-emscripten and wasm32-wasi ,大部分 os 模块不可用或行为有差异。进程相关 API (如 fork() , execve() ),信号 (如 kill() , wait() ),和资源 (如 nice() ) 不可用。其它像 getuid() and getpid() 是模拟的 (或存根)。
wasm32-emscripten
wasm32-wasi
fork()
execve()
kill()
wait()
nice()
getuid()
getpid()
注意
此模块中的所有函数会引发 OSError (或其子类) 若文件名和路径无效或不可访问,或拥有正确类型但不被操作系统所接受的其它自变量。
OSError
别名为内置 OSError 异常。
操作系统的名称从属模块导入。目前有注册下列名称: 'posix' , 'nt' , 'java' .
'posix'
'nt'
'java'
另请参阅
sys.platform 有更细粒度。 os.uname() 给出系统从属版本信息。
sys.platform
os.uname()
The platform 模块提供系统身份的详细校验。
platform
在 Python 中,文件名、命令行自变量及环境变量都使用字符串类型表示。在某些系统,将它们传递给操作系统之前,有必要解码这些字符串到 (或来自) 字节。Python 使用 文件系统编码和错误处理程序 来履行这种转换 (见 sys.getfilesystemencoding() ).
sys.getfilesystemencoding()
The 文件系统编码和错误处理程序 的配置是在 Python 启动时通过 PyConfig_Read() 函数:见 filesystem_encoding and filesystem_errors 成员对于 PyConfig .
PyConfig_Read()
filesystem_encoding
filesystem_errors
PyConfig
3.1 版改变: 在某些系统,使用文件系统编码转换可能失败。在这种情况下,Python 使用 surrogateescape (替代转义) 编码错误处理程序 , which means that undecodable bytes are replaced by a Unicode character U+DC xx on decoding, and these are again translated to the original byte on encoding.
The 文件系统编码 必须保证成功解码 128 以下的所有字节。若文件系统编码提供此保证失败,API 函数会引发 UnicodeError .
UnicodeError
另请参阅 区域设置编码 .
Added in version 3.7: 见 PEP 540 了解更多细节。
Python UTF-8 模式忽略 区域设置编码 并强制使用 UTF-8 编码:
使用 UTF-8 作为 文件系统编码 .
sys.getfilesystemencoding() 返回 'utf-8' .
'utf-8'
locale.getpreferredencoding() 返回 'utf-8' ( do_setlocale 自变量不起作用)。
locale.getpreferredencoding()
sys.stdin , sys.stdout ,和 sys.stderr 都使用 UTF-8 作为它们的文本编码,采用 surrogateescape 错误处理程序 被启用对于 sys.stdin and sys.stdout ( sys.stderr 继续使用 backslashreplace 如它在默认区域设置感知模式下所做的)
sys.stdin
sys.stdout
sys.stderr
surrogateescape
backslashreplace
在 Unix, os.device_encoding() 返回 'utf-8' 而不是设备编码。
os.device_encoding()
注意,可以按 UTF-8 模式覆盖标准流设置通过 PYTHONIOENCODING (就像它们可以在默认区域设置感知模式下)。
PYTHONIOENCODING
因此,改变这些更低级的 API,其它更高级 API 还会显露不同默认行为:
使用 UTF-8 编码将命令行自变量,环境变量及文件名解码成文本。
os.fsdecode() and os.fsencode() 使用 UTF-8 编码。
os.fsdecode()
os.fsencode()
open() , io.open() ,和 codecs.open() 默认使用 UTF-8 编码。不管怎样,它们默认仍使用严格错误处理程序,所以试图以文本模式打开二进制文件可能引发异常而不是产生无感觉数据。
io.open()
codecs.open()
The Python UTF-8 模式 被启用若 LC_CTYPE 区域设置为 C or POSIX 在 Python 启动时 (见 PyConfig_Read() 函数)。
C
POSIX
可以启用/禁用它使用 -X utf8 命令行选项和 PYTHONUTF8 环境变量。
-X utf8
PYTHONUTF8
若 PYTHONUTF8 环境变量根本未设置,则解释器默认使用当前区域设置, 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.
PYTHONCOERCECLOCALE
Python UTF-8 模式只可以在 Python 启动时启用。它的值可以读取自 sys.flags.utf8_mode .
sys.flags.utf8_mode
另请参阅 UTF-8 模式在 Windows 和 文件系统编码和错误处理程序 .
Python 3.15 将使 Python UTF-8 模式 默认。
这些函数和数据项提供信息并运转于当前进程和用户。
返回进程控制终端对应的文件名。
可用性 :Unix,非 Emscripten,非 WASI。
A 映射 对象的键和值是表示进程环境的字符串。例如, environ['HOME'] 是 Home (主) 目录的路径名 (在某些平台),且相当于 getenv("HOME") 在 C。
environ['HOME']
getenv("HOME")
捕获此映射,当首次 os 模块被导入,通常在 Python 启动期间,属于处理 site.py 。在此时间后对环境做出的改变,不会反射在 os.environ , 除了做出的改变是通过修改 os.environ 直接。
site.py
os.environ
此映射可用于修改环境及查询环境。 putenv() 将被自动调用当映射被修改时。
putenv()
在 Unix,键和值使用 sys.getfilesystemencoding() and 'surrogateescape' 错误处理程序。可以使用 environb 若愿意使用不同的编码。
'surrogateescape'
environb
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' .
environ['monty'] = 'python'
'MONTY'
'python'
调用 putenv() 直接不改变 os.environ ,因此最好修改 os.environ .
在某些平台,包括 FreeBSD 和 macOS,设置 environ 可能导致内存泄漏。参考系统文档编制了解 putenv() .
environ
可以删除此映射中的项以取消环境变量设置。 unsetenv() 会被自动调用当删除项从 os.environ ,和当某一 pop() or clear() 方法被调用。
unsetenv()
pop()
clear()
3.9 版改变: 更新支持 PEP 584 的合并 ( | ) 和更新 ( |= ) 运算符。
|
|=
字节版本的 environ : 映射 对象的键/值两者都是 bytes 对象表示进程环境。 environ and environb 是同步的 (修改 environb 更新 environ ,反之亦然)。
bytes
environb 才可用,若 supports_bytes_environ is True .
supports_bytes_environ
True
Added in version 3.2.
这些函数的描述,位于 文件和目录 .
编码 像路径 filename 到 文件系统编码和错误处理程序 ;返回 bytes 不变。
fsdecode() 是反函数。
fsdecode()
3.6 版改变: 添加支持以接受对象实现 os.PathLike 接口。
os.PathLike
解码 像路径 filename 从 文件系统编码和错误处理程序 ;返回 str 不变。
str
fsencode() 是反函数。
fsencode()
返回路径的文件系统表示。
若 str or bytes 被传入,它将不变返回。否则 __fspath__() 被调用并返回其值,若它是 str or bytes 对象。在所有其它情况下, TypeError 被引发。
__fspath__()
TypeError
Added in version 3.6.
An 抽象基类 用于表示文件系统路径的对象,如 pathlib.PurePath .
pathlib.PurePath
返回对象的文件系统表示。
方法仅应返回 str or bytes 对象,优选 str .
返回值对于环境变量 key 以字符串形式若存在,或 default 若它没有。 key 字符串。注意由于 getenv() 使用 os.environ ,映射的 getenv() 同样也是在导入时捕获的,但函数可能不反射未来环境变化。
getenv()
在 Unix,解码键和值采用 sys.getfilesystemencoding() and 'surrogateescape' 错误处理程序。可以使用 os.getenvb() 若愿意使用不同的编码。
os.getenvb()
可用性 :Unix、Windows。
返回值对于环境变量 key 以字节形式若存在,或 default 若它没有。 key 必须是 bytes。注意,由于 getenvb() 使用 os.environb ,映射的 getenvb() 同样也是在导入时捕获的,但函数可能不反射未来环境变化。
getenvb()
os.environb
getenvb() 才可用,若 supports_bytes_environ is True .
可用性 :Unix。
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 被使用。
None
返回当前进程的有效组 ID。这对应当前进程正执行文件中的 set id 位。
返回当前进程的有效用户 ID。
返回当前进程的真实组 ID。
函数在 Emscripten 和 WASI 是存根,见 WebAssembly 平台 了解更多信息。
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.
Added in version 3.3.
返回关联当前进程的补充组 ID 的列表。
在 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() .
getgroups()
10.5
setgroups()
MACOSX_DEPLOYMENT_TARGET
sysconfig.get_config_var()
返回进程控制终端的登录用户名。对于大多数目的,更有用的是使用 getpass.getuser() 因为后者校验环境变量 LOGNAME or USERNAME 以找出用户是谁,并回退到 pwd.getpwuid(os.getuid())[0] 以获取当前真实用户 ID 的登录名。
getpass.getuser()
LOGNAME
USERNAME
pwd.getpwuid(os.getuid())[0]
可用性 :Unix、Windows、非 Emscripten、非 WASI。
返回进程的进程组 ID 采用进程 ID pid 。若 pid 为 0,返回当前进程的进程组 ID。
返回当前进程组的 ID。
返回当前进程 ID。
返回父级的进程 ID。当父级进程已退出时,在 Unix 返回 ID 是 init 进程 (1) 之一,在 Windows 仍是相同 ID,可能已被另一进程所重用。
3.2 版改变: 添加支持 Windows。
获取程序调度优先级。值 which 是某一 PRIO_PROCESS , PRIO_PGRP ,或 PRIO_USER ,和 who 的解释相对于 which (进程标识符为 PRIO_PROCESS ,进程组标识符为 PRIO_PGRP ,和用户 ID 为 PRIO_USER )。0 值对于 who (分别) 表示调用进程、调用进程的进程组、或调用进程的真实用户 ID。
PRIO_PROCESS
PRIO_PGRP
PRIO_USER
参数用于 getpriority() and setpriority() 函数。
getpriority()
setpriority()
可用性 : macOS
3.12 版添加。
返回表示当前进程真实、有效及保存用户 ID 的元组 (ruid, euid, suid)。
返回表示当前进程真实、有效及保存组 ID 的元组 (rgid, egid, sgid)。
返回当前进程的真实用户 ID。
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.
设置环境变量命名 key 到字符串 value 。对环境的这种改变会影响子进程的启动采用 os.system() , popen() or fork() and execv() .
os.system()
popen()
execv()
赋值项在 os.environ 会被自动翻译成相应调用 putenv() ;不管怎样,调用 putenv() 不更新 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.putenv 采用自变量 key , value .
os.putenv
key
value
3.9 版改变: 函数现在始终可用。
设置当前进程的有效组 ID。
设置当前进程的有效用户 ID。
设置当前进程的组 ID。
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.
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().
Reassociate the current thread with a Linux namespace. See the setns(2) and namespaces(7) man pages for more details.
若 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).
/proc/pid/ns/
setns()
0
Since Linux 5.8, fd may refer to a PID file descriptor obtained from pidfd_open() 。在此情况下, 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 ,如 setns(fd, os.CLONE_NEWUTS | os.CLONE_NEWPID) . The caller’s memberships in unspecified namespaces are left unchanged.
pidfd_open()
setns(fd, os.CLONE_NEWUTS | os.CLONE_NEWPID)
fd can be any object with a fileno() method, or a raw file descriptor.
fileno()
This example reassociates the thread with the init process’s network namespace:
init
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.
The unshare() 函数。
unshare()
调用系统调用 setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics.
setpgrp()
setpgrp(0, 0)
调用系统调用 setpgid() to set the process group id of the process with id pid to the process group with id pgrp 。见 Unix 手册了解语义。
setpgid()
设置程序调度优先级。值 which 是某一 PRIO_PROCESS , PRIO_PGRP ,或 PRIO_USER ,和 who 的解释相对于 which (进程标识符为 PRIO_PROCESS ,进程组标识符为 PRIO_PGRP ,和用户 ID 为 PRIO_USER )。0 值对于 who (分别) 表示调用进程、调用进程的进程组、或调用进程的真实用户 ID。 priority 是在 -20 到 19 范围内的值。默认优先级为 0;较低优先级导致更利于调度。
设置当前进程的真实有效组 ID。
设置当前进程的真实、有效及保存组 ID。
设置当前进程的真实、有效及保存用户 ID。
设置当前进程的真实和有效用户 ID。
调用系统调用 getsid() 。见 Unix 手册了解语义。
getsid()
调用系统调用 setsid() 。见 Unix 手册了解语义。
setsid()
设置当前进程的用户 ID。
Return the error message corresponding to the error code in code . On platforms where strerror() 返回 NULL when given an unknown error number, ValueError 被引发。
strerror()
NULL
ValueError
True 若环境的本机 OS 类型是字节 (如 False 在 Windows)。
False
设置当前数值 umask 并返回先前 umask。
返回当前操作系统标识信息。返回值是具有 5 属性的对象:
sysname - 操作系统名称
sysname
nodename - 网络中的机器名称 (实现定义)
nodename
release - 操作系统发行
release
version - 操作系统版本
version
machine - 硬件标识符
machine
For backwards compatibility, this object is also iterable, behaving like a five-tuple containing sysname , nodename , release , version ,和 machine in that order.
某些系统截取 nodename 至 8 个字符或至前导分量;获取主机名的更优办法是 socket.gethostname() 或者甚至 socket.gethostbyaddr(socket.gethostname()) .
socket.gethostname()
socket.gethostbyaddr(socket.gethostname())
3.3 版改变: 返回类型从元组更改为具有命名属性的像元组对象。
取消设置 (删除) 环境变量命名 key 。对环境的这种改变会影响子进程的启动采用 os.system() , popen() or fork() and execv() .
Deletion of items in os.environ is automatically translated into a corresponding call to unsetenv() ;不管怎样,调用 unsetenv() 不更新 os.environ , so it is actually preferable to delete items of os.environ .
引发 审计事件 os.unsetenv 采用自变量 key .
os.unsetenv
3.9 版改变: 函数现在始终可用,且在 Windows 也可用。
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 自变量为 0 , no changes are made to the calling process’s execution context.
可用性 : Linux >= 2.6.16.
The setns() 函数。
Flags to the unshare() function, if the implementation supports them. See unshare(2) in the Linux manual for their exact effect and availability.
这些函数创建新的 文件对象 。(另请参阅 open() 用于打开文件描述符。)
返回的打开文件对象被连接到文件描述符 fd 。这是别名化的 open() 内置函数且接受相同自变量。唯一差异是第一自变量 fdopen() 必须始终为整数。
fdopen()
这些函数运转于使用文件描述符引用的 I/O 流。
文件描述符是对应当前进程打开文件的小整数。例如,标准输入文件描述符通常是 0,标准输出是 1,标准错误是 2。然后,进一步由进程打开的文件会被赋值 3、4、5,依此类推。"文件描述符" 名称有点欺骗性;在 Unix 平台,套接字和管道也被文件描述符引用。
The fileno() 方法可以用于获得文件描述符关联 文件对象 当要求时。 注意,直接使用文件描述符将绕过文件对象方法,忽略譬如数据内部缓冲方面。
关闭文件描述符 fd .
此函数旨在低级 I/O 且必须应用于文件描述符如返回通过 os.open() or pipe() 。要关闭 "文件对象" 返回通过内置函数 open() 或通过 popen() or fdopen() ,使用其 close() 方法。
os.open()
pipe()
close()
关闭所有文件描述符从 fd_low (包括在内) 到 fd_high (排除),忽略错误。相当于 (但更快相比):
for fd in range(fd_low, fd_high): try: os.close(fd) except OSError: pass
拷贝 count 字节从文件描述符 src , starting from offset offset_src , to file descriptor dst , starting from offset offset_dst 。若 offset_src is None ,那么 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 被引发采用 errno 设为 errno.EXDEV .
errno
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.
在 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.
os.copy_file_range()
可用性 :采用 glibc >= 2.27 的 Linux >= 4.5。
Added in version 3.8.
返回设备编码描述字符串关联 fd 若它被连接到终端;否则返回 None .
在 Unix,若 Python UTF-8 模式 被启用,返回 'UTF-8' 而不是设备编码。
'UTF-8'
3.10 版改变: 在 Unix,函数现在实现了 Python UTF-8 模式。
返回复制的文件描述符 fd 。新文件描述符 不可继承 .
在 Windows,当复制标准流 (0:stdin、1:stdout、2:stderr) 时, 新文件描述符 可继承 .
可用性 :非 WASI。
3.4 版改变: 现在,新文件描述符不可继承。
复制文件描述符 fd to fd2 ,首先关闭后者若有必要。返回 fd2 。新文件描述符 可继承 默认情况下或不可继承若 可继承 is False .
3.4 版改变: 添加可选 可继承 参数。
3.7 版改变: 返回 fd2 当成功时。先前, None 总是被返回。
更改模式对于文件给出通过 fd 到数值 mode 。见文档为 chmod() 了解可能值对于 mode 。从 Python 3.3 起,这相当于 os.chmod(fd, mode) .
chmod()
os.chmod(fd, mode)
引发 审计事件 os.chmod 采用自变量 path , mode , dir_fd .
os.chmod
path
mode
dir_fd
函数在 Emscripten 和 WASI 是受限制,见 WebAssembly 平台 了解更多信息。
更改所有者和组 ID 对于文件给出通过 fd 到数值 uid and gid 。要使某一 ID 留下不变,将它设为 -1。见 chown() 。从 Python 3.3 起,这相当于 os.chown(fd, uid, gid) .
chown()
os.chown(fd, uid, gid)
引发 审计事件 os.chown 采用自变量 path , uid , gid , dir_fd .
os.chown
uid
gid
强制写入文件采用文件描述符 fd 到磁盘。不强制更新元数据。
该函数不可用于 MacOS。
返回打开文件相关的系统配置信息。 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.
pathconf_names
若 name 是字符串且未知, ValueError 被引发。若特定值对于 name 主机系统不支持,即使包括在 pathconf_names , OSError 被引发采用 errno.EINVAL 对于错误编号。
errno.EINVAL
从 Python 3.3 起,这相当于 os.pathconf(fd, name) .
os.pathconf(fd, name)
获取状态对于文件描述符 fd 。返回 stat_result 对象。
stat_result
从 Python 3.3 起,这相当于 os.stat(fd) .
os.stat(fd)
The stat() 函数。
stat()
Return information about the filesystem containing the file associated with file descriptor fd ,像 statvfs() 。从 Python 3.3 起,这相当于 os.statvfs(fd) .
statvfs()
os.statvfs(fd)
强制写入文件采用文件描述符 fd 到磁盘。在 Unix,这调用本机 fsync() 函数;在 Windows,MS _commit() 函数。
fsync()
_commit()
若正开始采用缓冲 Python 文件对象 f ,首先做 f.flush() ,然后做 os.fsync(f.fileno()) ,以确保所有内部缓冲关联的 f 被写入磁盘。
f.flush()
os.fsync(f.fileno())
截取文件所对应的文件描述符 fd ,因此最多 length 字节按大小。从 Python 3.3 起,这相当于 os.truncate(fd, length) .
os.truncate(fd, length)
引发 审计事件 os.truncate 采用自变量 fd , length .
os.truncate
fd
length
3.5 版改变: 添加支持 Windows
获取文件描述符的阻塞模式: False 若 O_NONBLOCK 标志有设置, True 若标志被清零。
O_NONBLOCK
另请参阅 set_blocking() and socket.socket.setblocking() .
set_blocking()
socket.socket.setblocking()
On Windows, this function is limited to pipes.
Added in version 3.5.
Changed in version 3.12: Added support for pipes on Windows.
返回 True 若文件描述符 fd 被打开 且已连接到像 tty 设备,否则 False .
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.
F_LOCK
F_TLOCK
F_ULOCK
F_TEST
引发 审计事件 os.lockf 采用自变量 fd , cmd , len .
os.lockf
cmd
len
标志指定什么动作 lockf() 会接受。
lockf()
Prepare the tty of which fd is a file descriptor for a new login session. Make the calling process a session leader; make the tty the controlling tty, the stdin, the stdout, and the stderr of the calling process; close fd.
Added in version 3.11.
Set the current position of file descriptor fd to position pos , modified by whence , and return the new position in bytes relative to the start of the file. Valid values for whence 是:
SEEK_SET or 0 – set pos relative to the beginning of the file
SEEK_SET
SEEK_CUR or 1 – set pos relative to the current file position
SEEK_CUR
1
SEEK_END or 2 – set pos relative to the end of the file
SEEK_END
2
SEEK_HOLE – set pos to the next data location, relative to pos
SEEK_HOLE
SEEK_DATA – set pos to the next data hole, relative to pos
SEEK_DATA
3.3 版改变: Add support for SEEK_HOLE and SEEK_DATA .
参数用于 lseek() 函数和 seek() method on 像文件对象 , for whence to adjust the file position indicator.
lseek()
seek()
Adjust the file position relative to the beginning of the file.
Adjust the file position relative to the current file position.
Adjust the file position relative to the end of the file.
Their values are 0, 1, and 2, respectively.
参数用于 lseek() 函数和 seek() method on 像文件对象 , for seeking file data and holes on sparsely allocated files.
Adjust the file offset to the next location containing data, relative to the seek position.
Adjust the file offset to the next location containing a hole, relative to the seek position. A hole is defined as a sequence of zeros.
These operations only make sense for filesystems that support them.
可用性 : Linux >= 3.1, macOS, Unix
打开文件 path 和设置各种标志根据 flags 且其模式可能根据 mode 。当计算 mode ,会先屏蔽掉当前 umask 值。返回新近打开文件的文件描述符。新文件描述符 不可继承 .
对于 flags 和 mode 值的描述,见 C 运行时文档编制;flags 常量 (像 O_RDONLY and O_WRONLY ) 的定义在 os 模块。尤其,在 Windows 添加 O_BINARY 需要以二进制模式打开文件。
O_RDONLY
O_WRONLY
O_BINARY
此函数可以支持 相对于目录描述符的路径 采用 dir_fd 参数。
引发 审计事件 open 采用自变量 path , mode , flags .
open
flags
此函数旨在低级 I/O。对于正常用法,使用内置函数 open() ,其返回 文件对象 with read() and write() 方法 (及更多)。要包裹文件对象的文件描述符,使用 fdopen() .
read()
write()
3.3 版改变: 添加 dir_fd 参数。
3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,函数现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。
InterruptedError
3.6 版改变: 接受 像路径对象 .
下列常量是选项对于 flags 参数用于 open() 函数。可以组合它们使用按位 OR 运算符 | 。它们中的一些不可用于所有平台。对于它们的可用性和用法的描述,请翻阅 open(2) 手册页在 Unix 或 MSDN 在 Windows。
以上常量只可用于 Unix 和 Windows。
以上常量只可用于 Unix。
3.3 版改变: 添加 O_CLOEXEC 常量。
O_CLOEXEC
以上常量只可用于 Windows。
以上常量只可用于 macOS。
3.10 版改变: 添加 O_EVTONLY , O_FSYNC , O_SYMLINK and O_NOFOLLOW_ANY 常量。
O_EVTONLY
O_FSYNC
O_SYMLINK
O_NOFOLLOW_ANY
以上常量是扩展,且不存在若 C 库未定义它们。
3.4 版改变: 添加 O_PATH 在支持它的系统中。添加 O_TMPFILE ,只可用于 Linux 内核 3.11 或更高版本。
O_PATH
O_TMPFILE
打开新的伪终端对。返回一对文件描述符 (master, slave) for the pty and the tty, respectively. The new file descriptors are 不可继承 . For a (slightly) more portable approach, use the pty 模块。
(master, slave)
pty
3.4 版改变: 新文件描述符现在不可继承。
创建管道。返回一对文件描述符 (r, w) 分别用于读取和写入。新文件描述符 不可继承 .
(r, w)
创建管道采用 flags 原子设置。 flags 可以被构造通过将这些值中的一个或多个 OR 到一起: O_NONBLOCK , O_CLOEXEC 。返回一对文件描述符 (r, w) usable for reading and writing, respectively.
Ensures that enough disk space is allocated for the file specified by fd starting from offset and continuing for len 字节。
可用性 :Unix、非 Emscripten。
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 起始于 offset and continuing for len 字节。 advice 是某一 POSIX_FADV_NORMAL , POSIX_FADV_SEQUENTIAL , POSIX_FADV_RANDOM , POSIX_FADV_NOREUSE , POSIX_FADV_WILLNEED or POSIX_FADV_DONTNEED .
POSIX_FADV_NORMAL
POSIX_FADV_SEQUENTIAL
POSIX_FADV_RANDOM
POSIX_FADV_NOREUSE
POSIX_FADV_WILLNEED
POSIX_FADV_DONTNEED
Flags that can be used in advice in posix_fadvise() that specify the access pattern that is likely to be used.
posix_fadvise()
读取最多 n 字节从文件描述符 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.
Read from a file descriptor fd at a position of offset into mutable 像字节对象 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
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() 值 'SC_IOV_MAX' ) on the number of buffers that can be used.
sysconf()
'SC_IOV_MAX'
Combine the functionality of os.readv() and os.pread() .
os.readv()
os.pread()
可用性 : Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.
Using flags requires Linux >= 4.6.
Added in version 3.7.
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 .
-1
errno.EAGAIN
可用性 : Linux >= 4.14.
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 标志。
O_DIRECT
可用性 : Linux >= 4.6.
写入字节字符串按 str 到文件描述符 fd at position of offset , leaving the file offset unchanged.
返回实际写入的字节数。
写入 buffers contents to file descriptor fd at a offset offset , leaving the file offset unchanged. buffers must be a sequence of 像字节对象 . Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.
RWF_DSYNC
RWF_SYNC
RWF_APPEND
Return the total number of bytes actually written.
Combine the functionality of os.writev() and os.pwrite() .
os.writev()
os.pwrite()
Provide a per-write equivalent of the O_DSYNC os.open() flag. This flag effect applies only to the data range written by the system call.
O_DSYNC
可用性 : Linux >= 4.7.
Provide a per-write equivalent of the O_SYNC os.open() flag. This flag effect applies only to the data range written by the system call.
O_SYNC
Provide a per-write equivalent of the O_APPEND os.open() flag. This flag is meaningful only for os.pwritev() , and its effect applies only to the data range written by the system call. The offset argument does not affect the write operation; the data is always appended to the end of the file. However, if the offset 自变量为 -1 , the current file offset is updated.
O_APPEND
os.pwritev()
可用性 : Linux >= 4.16.
Added in version 3.10.
读取最多 n 字节从文件描述符 fd .
此函数旨在低级 I/O 且必须应用于文件描述符如返回通过 os.open() or pipe() . To read a “file object” returned by the built-in function open() 或通过 popen() or fdopen() ,或 sys.stdin ,使用其 read() or readline() 方法。
readline()
拷贝 count 字节从文件描述符 in_fd 到文件描述符 out_fd 起始于 offset 。返回发送字节数。当到达 EOF (文件末尾) 时返回 0 .
第一函数表示法所有平台都支持,若平台有定义 sendfile() .
sendfile()
在 Linux,若 offset 被给定为 None , the bytes are read from the current position of in_fd and the position of in_fd is updated.
The second case may be used on macOS and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after the data from in_fd is written. It returns the same as the first case.
在 macOS 和 FreeBSD,值 0 for count specifies to send until the end of in_fd is reached.
所有平台支持套接字作为 out_fd 文件描述符,且某些平台还允许其它类型 (如:常规文件、管道)。
跨平台应用程序不应使用 headers , trailers and flags 自变量。
对于高级包裹器 sendfile() ,见 socket.socket.sendfile() .
socket.socket.sendfile()
3.9 版改变: 参数 out and in 被重命名为 out_fd and in_fd .
参数用于 sendfile() 函数,若实现支持它们。
参数用于 sendfile() function, if the implementation supports it. The data won’t be cached in the virtual memory and will be freed afterwards.
设置指定文件描述符的阻塞模式。设置 O_NONBLOCK 标志若阻塞为 False ,否则清零标志。
另请参阅 get_blocking() and socket.socket.setblocking() .
get_blocking()
Transfer count 字节从文件描述符 src , starting from offset offset_src , to file descriptor dst , starting from offset offset_dst . At least one of the file descriptors must refer to a pipe. If offset_src is None ,那么 src is read from the current position; respectively for offset_dst . The offset associated to the file descriptor that refers to a pipe must be None . The files pointed to by src and dst must reside in the same filesystem, otherwise an OSError 被引发采用 errno 设为 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. The copy is done as if both files are opened as binary.
Upon successful completion, returns the number of bytes spliced to or from the pipe. A return value of 0 means end of input. If src refers to a pipe, then this means that there was no data to transfer, and it would not make sense to block because there are no writers connected to the write end of the pipe.
可用性 : Linux >= 2.6.17 with glibc >= 2.5
Read from a file descriptor fd into a number of mutable 像字节对象 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 process group associated with the terminal given by fd (an open file descriptor as returned by os.open() ).
可用性 :Unix,非 WASI。
Set the process group associated with the terminal given by fd (an open file descriptor as returned by os.open() ) 到 pg .
Return a string which specifies the terminal device associated with file descriptor fd 。若 fd is not associated with a terminal device, an exception is raised.
写入字节字符串按 str 到文件描述符 fd .
此函数旨在低级 I/O 且必须应用于文件描述符如返回通过 os.open() or pipe() . To write a “file object” returned by the built-in function open() 或通过 popen() or fdopen() ,或 sys.stdout or sys.stderr ,使用其 write() 方法。
Write the contents of buffers 到文件描述符 fd . buffers must be a sequence of 像字节对象 . 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.
Return the size of the terminal window as (columns, lines) , tuple of type terminal_size .
(columns, lines)
terminal_size
可选自变量 fd (默认 STDOUT_FILENO , or standard output) specifies which file descriptor should be queried.
STDOUT_FILENO
If the file descriptor is not connected to a terminal, an OSError 被引发。
shutil.get_terminal_size() is the high-level function which should normally be used, os.get_terminal_size is the low-level implementation.
shutil.get_terminal_size()
os.get_terminal_size
A subclass of tuple, holding (columns, lines) of the terminal window size.
终端窗口的宽度 (以字符为单位)。
终端窗口的高度 (以字符为单位)。
Added in version 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* functions, all inheritable handles and all inheritable file descriptors are inherited. Using the subprocess module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the close_fds 参数为 False .
spawn*
subprocess
在 WebAssembly 平台 wasm32-emscripten and wasm32-wasi , the file descriptor cannot be modified.
Get the “inheritable” flag of the specified file descriptor (a boolean).
Set the “inheritable” flag of the specified file descriptor.
Get the “inheritable” flag of the specified handle (a boolean).
可用性 :Windows。
Set the “inheritable” flag of the specified handle.
在某些 Unix 平台,这些函数中的很多均支持一个或多个这些特征:
指定文件描述符: Normally the path argument provided to functions in the os module must be a string specifying a file path. However, some functions now alternatively accept an open file descriptor for their path argument. The function will then operate on the file referred to by the descriptor. (For POSIX systems, Python will call the variant of the function prefixed with f (e.g. call fchdir 而不是 chdir ).)
f
fchdir
chdir
You can check whether or not path can be specified as a file descriptor for a particular function on your platform using os.supports_fd . If this functionality is unavailable, using it will raise a NotImplementedError .
os.supports_fd
NotImplementedError
If the function also supports dir_fd or follow_symlinks arguments, it’s an error to specify one of those when supplying path as a file descriptor.
paths relative to directory descriptors: 若 dir_fd 不是 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 variant of the function with an at suffix and possibly prefixed with f (e.g. call faccessat 而不是 access ).
at
faccessat
access
You can check whether or not dir_fd is supported for a particular function on your platform using os.supports_dir_fd . If it’s unavailable, using it will raise a NotImplementedError .
os.supports_dir_fd
不遵循符号链接: 若 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 rather than the file pointed to by the link. (For POSIX systems, Python will call the l... variant of the function.)
l...
You can check whether or not follow_symlinks is supported for a particular function on your platform using os.supports_follow_symlinks . If it’s unavailable, using it will raise a NotImplementedError .
os.supports_follow_symlinks
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 应该为 F_OK to test the existence of path , or it can be the inclusive OR of one or more of R_OK , W_OK ,和 X_OK to test permissions. Return True if access is allowed, False if not. See the Unix man page access(2) 了解更多信息。
F_OK
R_OK
W_OK
X_OK
此函数可以支持指定 相对于目录描述符的路径 and 不遵循符号链接 .
若 effective_ids is True , 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 . If it is unavailable, using it will raise a NotImplementedError .
access()
os.supports_effective_ids
使用 access() to check if a user is authorized to e.g. open a file before actually doing so using 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 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() 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 版改变: 添加 dir_fd , effective_ids ,和 follow_symlinks 参数。
值要传递作为 mode 参数对于 access() to test the existence, readability, writability and executability of path ,分别。
将当前工作目录更改成 path .
此函数可以支持 指定文件描述符 。描述符必须引用打开目录,而不是打开文件。
此函数可以引发 OSError 和子类譬如 FileNotFoundError , PermissionError ,和 NotADirectoryError .
FileNotFoundError
PermissionError
NotADirectoryError
引发 审计事件 os.chdir 采用自变量 path .
os.chdir
3.3 版改变: 添加支持指定 path 作为文件描述符在某些平台。
设置标志为 path 到数值 flags . flags may take a combination (bitwise OR) of the following values (as defined in the stat 模块):
stat
stat.UF_NODUMP
stat.UF_IMMUTABLE
stat.UF_APPEND
stat.UF_OPAQUE
stat.UF_NOUNLINK
stat.UF_COMPRESSED
stat.UF_HIDDEN
stat.SF_ARCHIVED
stat.SF_IMMUTABLE
stat.SF_APPEND
stat.SF_NOUNLINK
stat.SF_SNAPSHOT
此函数可以支持 不遵循符号链接 .
引发 审计事件 os.chflags 采用自变量 path , flags .
os.chflags
3.3 版改变: 添加 follow_symlinks 参数。
改变模式为 path 到数值 mode . mode may take one of the following values (as defined in the stat module) or bitwise ORed combinations of them:
stat.S_ISUID
stat.S_ISGID
stat.S_ENFMT
stat.S_ISVTX
stat.S_IREAD
stat.S_IWRITE
stat.S_IEXEC
stat.S_IRWXU
stat.S_IRUSR
stat.S_IWUSR
stat.S_IXUSR
stat.S_IRWXG
stat.S_IRGRP
stat.S_IWGRP
stat.S_IXGRP
stat.S_IRWXO
stat.S_IROTH
stat.S_IWOTH
stat.S_IXOTH
此函数可以支持 指定文件描述符 , 相对于目录描述符的路径 and 不遵循符号链接 .
尽管 Windows 支持 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 版改变: 添加支持指定 path 按打开文件描述符,和 dir_fd and follow_symlinks 自变量。
更改所有者和组 ID 为 path 到数值 uid and gid 。要使某一 ID 留下不变,将它设为 -1。
见 shutil.chown() for a higher-level function that accepts names in addition to numeric ids.
shutil.chown()
3.6 版改变: 支持 像路径对象 .
Change the root directory of the current process to path .
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) .
os.chdir(fd)
返回当前工作目录的字符串表示。
Return a bytestring representing the current working directory.
3.8 版改变: The function now uses the UTF-8 encoding on Windows, rather than the ANSI code page: see PEP 529 for the rationale. The function is no longer deprecated on Windows.
设置标志为 path 到数值 flags ,像