os — 杂项操作系统接口

源代码: Lib/os.py


此模块提供使用操作系统从属功能的可移植方式。若仅仅想要读取或写入文件,见 open() ,若想要操纵路径,见 os.path 模块,若想要在命令行中读取所有文件中的所有行,见 fileinput 模块。对于创建临时文件和目录,见 tempfile 模块,对于高级文件和目录处理,见 shutil 模块。

有关这些函数的可用性的注意事项:

  • Python 所有内置操作系统依赖模块的设计是这样的,只要相同功能可用,就使用相同接口;例如,函数 os.stat(path) 返回的统计信息关于 path 按相同格式 (恰好发源于 POSIX 接口)。

  • 特定操作系统的特有扩展也可用透过 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() 是模拟的 (或存根)。

注意

此模块中的所有函数会引发 OSError (或其子类) 若文件名和路径无效或不可访问,或拥有正确类型但不被操作系统所接受的其它自变量。

exception os. error

别名为内置 OSError 异常。

os. name

操作系统的名称从属模块导入。目前有注册下列名称: 'posix' , 'nt' , 'java' .

另请参阅

sys.platform 有更细粒度。 os.uname() 给出系统从属版本信息。

platform 模块提供系统身份的详细校验。

文件名、命令行自变量和环境变量

在 Python 中,文件名、命令行自变量及环境变量都使用字符串类型表示。在某些系统,将它们传递给操作系统之前,有必要解码这些字符串到 (或来自) 字节。Python 使用 文件系统编码和错误处理程序 来履行这种转换 (见 sys.getfilesystemencoding() ).

文件系统编码和错误处理程序 的配置是在 Python 启动时通过 PyConfig_Read() 函数:见 filesystem_encoding and filesystem_errors 成员对于 PyConfig .

3.1 版改变: 在某些系统,使用文件系统编码转换可能失败。在这种情况下,Python 使用 surrogateescape (替代转义) 编码错误处理程序 ,意味着不可解码的 bytes 在解码时会被 Unicode 字符 U+DCxx 所替换,且这些在编码时会再次被翻译成原始 bytes。

文件系统编码 必须保证成功解码 128 以下的所有字节。若文件系统编码提供此保证失败,API 函数会引发 UnicodeError .

另请参阅 区域设置编码 .

Python UTF-8 模式

3.7 版新增: PEP 540 了解更多细节。

Python UTF-8 模式忽略 区域设置编码 并强制使用 UTF-8 编码:

注意,可以按 UTF-8 模式覆盖标准流设置通过 PYTHONIOENCODING (就像它们可以在默认区域设置感知模式下)。

因此,改变这些更低级的 API,其它更高级 API 还会显露不同默认行为:

  • 使用 UTF-8 编码将命令行自变量,环境变量及文件名解码成文本。

  • os.fsdecode() and os.fsencode() 使用 UTF-8 编码。

  • open() , io.open() ,和 codecs.open() 默认使用 UTF-8 编码。不管怎样,它们默认仍使用严格错误处理程序,所以试图以文本模式打开二进制文件可能引发异常而不是产生无感觉数据。

Python UTF-8 模式 被启用若 LC_CTYPE 区域设置为 C or POSIX 在 Python 启动时 (见 PyConfig_Read() 函数)。

可以启用/禁用它使用 -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.

Python UTF-8 模式只可以在 Python 启动时启用。它的值可以读取自 sys.flags.utf8_mode .

另请参阅 UTF-8 模式在 Windows 文件系统编码和错误处理程序 .

另请参阅

PEP 686

Python 3.15 将使 Python UTF-8 模式 默认。

进程参数

这些函数和数据项提供信息并运转于当前进程和用户。

os. ctermid ( )

返回进程控制终端对应的文件名。

可用性 :Unix,非 Emscripten,非 WASI。

os. environ

A 映射 对象的键和值是表示进程环境的字符串。例如, environ['HOME'] 是 Home (主) 目录的路径名 (在某些平台),且相当于 getenv("HOME") 在 C。

捕获此映射,当首次 os 模块被导入,通常在 Python 启动期间,属于处理 site.py 。在此时间后对环境做出的改变,不会反射在 os.environ , 除了做出的改变是通过修改 os.environ 直接。

此映射可用于修改环境及查询环境。 putenv() 将被自动调用当映射被修改时。

在 Unix,键和值使用 sys.getfilesystemencoding() and 'surrogateescape' 错误处理程序。可以使用 environb 若愿意使用不同的编码。

注意

调用 putenv() 直接不改变 os.environ ,因此最好修改 os.environ .

注意

在某些平台,包括 FreeBSD 和 macOS,设置 environ 可能导致内存泄漏。参考系统文档编制了解 putenv() .

可以删除此映射中的项以取消环境变量设置。 unsetenv() 会被自动调用当删除项从 os.environ ,和当某一 pop() or clear() 方法被调用。

3.9 版改变: 更新支持 PEP 584 的合并 ( | ) 和更新 ( |= ) 运算符。

os. environb

字节版本的 environ 映射 对象的键/值两者都是 bytes 对象表示进程环境。 environ and environb 是同步的 (修改 environb 更新 environ ,反之亦然)。

environb 才可用,若 supports_bytes_environ is True .

3.2 版新增。

3.9 版改变: 更新支持 PEP 584 的合并 ( | ) 和更新 ( |= ) 运算符。

os. chdir ( path )
os. fchdir ( fd )
os. getcwd ( )

这些函数的描述,位于 文件和目录 .

os. fsencode ( filename )

编码 像路径 filename 文件系统编码和错误处理程序 ;返回 bytes 不变。

fsdecode() 是反函数。

3.2 版新增。

3.6 版改变: 添加支持以接受对象实现 os.PathLike 接口。

os. fsdecode ( filename )

解码 像路径 filename 文件系统编码和错误处理程序 ;返回 str 不变。

fsencode() 是反函数。

3.2 版新增。

3.6 版改变: 添加支持以接受对象实现 os.PathLike 接口。

os. fspath ( path )

返回路径的文件系统表示。

str or bytes 被传入,它将不变返回。否则 __fspath__() 被调用并返回其值,若它是 str or bytes 对象。在所有其它情况下, TypeError 被引发。

3.6 版新增。

class os. PathLike

抽象基类 用于表示文件系统路径的对象,如 pathlib.PurePath .

3.6 版新增。

abstractmethod __fspath__ ( )

返回对象的文件系统表示。

方法仅应返回 str or bytes 对象,优选 str .

os. getenv ( key , default = None )

返回值对于环境变量 key 以字符串形式若存在,或 default 若它没有。 key 字符串。注意由于 getenv() 使用 os.environ ,映射的 getenv() 同样也是在导入时捕获的,但函数可能不反射未来环境变化。

在 Unix,解码键和值采用 sys.getfilesystemencoding() and 'surrogateescape' 错误处理程序。可以使用 os.getenvb() 若愿意使用不同的编码。

可用性 :Unix、Windows。

os. getenvb ( key , default = None )

返回值对于环境变量 key 以字节形式若存在,或 default 若它没有。 key 必须是 bytes。注意,由于 getenvb() 使用 os.environb ,映射的 getenvb() 同样也是在导入时捕获的,但函数可能不反射未来环境变化。

getenvb() 才可用,若 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 被使用。

3.2 版新增。

os. getegid ( )

返回当前进程的有效组 ID。这对应当前进程正执行文件中的 set id 位。

可用性 :Unix,非 Emscripten,非 WASI。

os. geteuid ( )

返回当前进程的有效用户 ID。

可用性 :Unix,非 Emscripten,非 WASI。

os. getgid ( )

返回当前进程的真实组 ID。

可用性 :Unix。

函数在 Emscripten 和 WASI 是存根,见 WebAssembly 平台 了解更多信息。

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,非 Emscripten,非 WASI。

3.3 版新增。

os. getgroups ( )

返回关联当前进程的补充组 ID 的列表。

可用性 :Unix,非 Emscripten,非 WASI。

注意

在 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 ( )

返回进程控制终端的登录用户名。对于大多数目的,更有用的是使用 getpass.getuser() 因为后者校验环境变量 LOGNAME or USERNAME 以找出用户是谁,并回退到 pwd.getpwuid(os.getuid())[0] 以获取当前真实用户 ID 的登录名。

可用性 :Unix、Windows、非 Emscripten、非 WASI。

os. getpgid ( pid )

返回进程的进程组 ID 采用进程 ID pid 。若 pid 为 0,返回当前进程的进程组 ID。

可用性 :Unix,非 Emscripten,非 WASI。

os. getpgrp ( )

返回当前进程组的 ID。

可用性 :Unix,非 Emscripten,非 WASI。

os. getpid ( )

返回当前进程 ID。

函数在 Emscripten 和 WASI 是存根,见 WebAssembly 平台 了解更多信息。

os. getppid ( )

返回父级的进程 ID。当父级进程已退出时,在 Unix 返回 ID 是 init 进程 (1) 之一,在 Windows 仍是相同 ID,可能已被另一进程所重用。

可用性 :Unix、Windows、非 Emscripten、非 WASI。

3.2 版改变: 添加支持 Windows。

os. getpriority ( which , who )

获取程序调度优先级。值 which 是某一 PRIO_PROCESS , PRIO_PGRP ,或 PRIO_USER ,和 who 的解释相对于 which (进程标识符为 PRIO_PROCESS ,进程组标识符为 PRIO_PGRP ,和用户 ID 为 PRIO_USER )。0 值对于 who (分别) 表示调用进程、调用进程的进程组、或调用进程的真实用户 ID。

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增。

os. PRIO_PROCESS
os. PRIO_PGRP
os. PRIO_USER

参数用于 getpriority() and setpriority() 函数。

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增。

os. getresuid ( )

返回表示当前进程真实、有效及保存用户 ID 的元组 (ruid, euid, suid)。

可用性 :Unix,非 Emscripten,非 WASI。

3.2 版新增。

os. getresgid ( )

返回表示当前进程真实、有效及保存组 ID 的元组 (rgid, egid, sgid)。

可用性 :Unix,非 Emscripten,非 WASI。

3.2 版新增。

os. getuid ( )

返回当前进程的真实用户 ID。

可用性 :Unix。

函数在 Emscripten 和 WASI 是存根,见 WebAssembly 平台 了解更多信息。

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,非 Emscripten,非 WASI。

3.2 版新增。

os. putenv ( key , value , / )

设置环境变量命名 key 到字符串 value 。对环境的这种改变会影响子进程的启动采用 os.system() , popen() or fork() and 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.

注意

在某些平台,包括 FreeBSD 和 macOS,设置 environ 可能导致内存泄漏。参考系统文档编制了解 putenv() .

引发 审计事件 os.putenv 采用自变量 key , value .

3.9 版改变: 函数现在始终可用。

os. setegid ( egid , / )

设置当前进程的有效组 ID。

可用性 :Unix,非 Emscripten,非 WASI。

os. seteuid ( euid , / )

设置当前进程的有效用户 ID。

可用性 :Unix,非 Emscripten,非 WASI。

os. setgid ( gid , / )

设置当前进程的组 ID。

可用性 :Unix,非 Emscripten,非 WASI。

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,非 Emscripten,非 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. setpgrp ( )

调用系统调用 setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics.

可用性 :Unix,非 Emscripten,非 WASI。

os. setpgid ( pid , pgrp , / )

调用系统调用 setpgid() to set the process group id of the process with id pid to the process group with id pgrp 。见 Unix 手册了解语义。

可用性 :Unix,非 Emscripten,非 WASI。

os. setpriority ( which , who , priority )

设置程序调度优先级。值 which 是某一 PRIO_PROCESS , PRIO_PGRP ,或 PRIO_USER ,和 who 的解释相对于 which (进程标识符为 PRIO_PROCESS ,进程组标识符为 PRIO_PGRP ,和用户 ID 为 PRIO_USER )。0 值对于 who (分别) 表示调用进程、调用进程的进程组、或调用进程的真实用户 ID。 priority 是在 -20 到 19 范围内的值。默认优先级为 0;较低优先级导致更利于调度。

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增。

os. setregid ( rgid , egid , / )

设置当前进程的真实有效组 ID。

可用性 :Unix,非 Emscripten,非 WASI。

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

设置当前进程的真实、有效及保存组 ID。

可用性 :Unix,非 Emscripten,非 WASI。

3.2 版新增。

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

设置当前进程的真实、有效及保存用户 ID。

可用性 :Unix,非 Emscripten,非 WASI。

3.2 版新增。

os. setreuid ( ruid , euid , / )

设置当前进程的真实和有效用户 ID。

可用性 :Unix,非 Emscripten,非 WASI。

os. getsid ( pid , / )

调用系统调用 getsid() 。见 Unix 手册了解语义。

可用性 :Unix,非 Emscripten,非 WASI。

os. setsid ( )

调用系统调用 setsid() 。见 Unix 手册了解语义。

可用性 :Unix,非 Emscripten,非 WASI。

os. setuid ( uid , / )

设置当前进程的用户 ID。

可用性 :Unix,非 Emscripten,非 WASI。

os. strerror ( code , / )

Return the error message corresponding to the error code in code . On platforms where strerror() 返回 NULL when given an unknown error number, ValueError 被引发。

os. supports_bytes_environ

True 若环境的本机 OS 类型是字节 (如 False 在 Windows)。

3.2 版新增。

os. umask ( mask , / )

设置当前数值 umask 并返回先前 umask。

函数在 Emscripten 和 WASI 是存根,见 WebAssembly 平台 了解更多信息。

os. uname ( )

返回当前操作系统标识信息。返回值是具有 5 属性的对象:

  • sysname - 操作系统名称

  • nodename - 网络中的机器名称 (实现定义)

  • release - 操作系统发行

  • version - 操作系统版本

  • 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()) .

可用性 :Unix。

3.3 版改变: 返回类型从元组更改为具有命名属性的像元组对象。

os. unsetenv ( key , / )

取消设置 (删除) 环境变量命名 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 .

3.9 版改变: 函数现在始终可用,且在 Windows 也可用。

文件对象创建

这些函数创建新的 文件对象 。(另请参阅 open() 用于打开文件描述符。)

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

返回的打开文件对象被连接到文件描述符 fd 。这是别名化的 open() 内置函数且接受相同自变量。唯一差异是第一自变量 fdopen() 必须始终为整数。

文件描述符操作

这些函数运转于使用文件描述符引用的 I/O 流。

文件描述符是对应当前进程打开文件的小整数。例如,标准输入文件描述符通常是 0,标准输出是 1,标准错误是 2。然后,进一步由进程打开的文件会被赋值 3、4、5,依此类推。"文件描述符" 名称有点欺骗性;在 Unix 平台,套接字和管道也被文件描述符引用。

fileno() 方法可以用于获得文件描述符关联 文件对象 当要求时。 注意,直接使用文件描述符将绕过文件对象方法,忽略譬如数据内部缓冲方面。

os. close ( fd )

关闭文件描述符 fd .

注意

此函数旨在低级 I/O 且必须应用于文件描述符如返回通过 os.open() or pipe() 。要关闭 "文件对象" 返回通过内置函数 open() 或通过 popen() or fdopen() ,使用其 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. copy_file_range ( src , dst , count , offset_src = None , offset_dst = None )

拷贝 count 字节从文件描述符 src , starting from offset offset_src , to file descriptor dst , starting from offset offset_dst 。若 offset_src is None, then src is read from the current position; respectively for offset_dst . The files pointed 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.

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

可用性 :采用 glibc >= 2.27 的 Linux >= 4.5。

3.8 版新增。

os. device_encoding ( fd )

返回设备编码描述字符串关联 fd 若它被连接到终端;否则返回 None .

在 Unix,若 Python UTF-8 模式 被启用,返回 'UTF-8' 而不是设备编码。

3.10 版改变: 在 Unix,函数现在实现了 Python UTF-8 模式。

os. dup ( fd , / )

返回复制的文件描述符 fd 。新文件描述符 不可继承 .

在 Windows,当复制标准流 (0:stdin、1:stdout、2:stderr) 时, 新文件描述符 inheritable .

可用性 :非 WASI。

3.4 版改变: 现在,新文件描述符不可继承。

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

复制文件描述符 fd to fd2 ,首先关闭后者若有必要。返回 fd2 。新文件描述符 inheritable 默认情况下或不可继承若 inheritable is False .

可用性 :非 WASI。

3.4 版改变: 添加可选 inheritable 参数。

3.7 版改变: 返回 fd2 当成功时。先前, None 总是被返回。

os. fchmod ( fd , mode )

更改模式对于文件给出通过 fd 到数值 mode 。见文档为 chmod() 了解可能值对于 mode 。从 Python 3.3 起,这相当于 os.chmod(fd, mode) .

引发 审计事件 os.chmod 采用自变量 path , mode , dir_fd .

可用性 :Unix。

函数在 Emscripten 和 WASI 是受限制,见 WebAssembly 平台 了解更多信息。

os. fchown ( fd , uid , gid )

更改所有者和组 ID 对于文件给出通过 fd 到数值 uid and gid 。要使某一 ID 留下不变,将它设为 -1。见 chown() 。从 Python 3.3 起,这相当于 os.chown(fd, uid, gid) .

引发 审计事件 os.chown 采用自变量 path , uid , gid , dir_fd .

可用性 :Unix。

函数在 Emscripten 和 WASI 是受限制,见 WebAssembly 平台 了解更多信息。

os. fdatasync ( fd )

强制写入文件采用文件描述符 fd 到磁盘。不强制更新元数据。

可用性 :Unix。

注意

该函数不可用于 MacOS。

os. fpathconf ( fd , name , / )

返回打开文件相关的系统配置信息。 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.

name 是字符串且未知, ValueError 被引发。若特定值对于 name 主机系统不支持,即使包括在 pathconf_names OSError 被引发采用 errno.EINVAL 对于错误编号。

从 Python 3.3 起,这相当于 os.pathconf(fd, name) .

可用性 :Unix。

os. fstat ( fd )

获取状态对于文件描述符 fd 。返回 stat_result 对象。

从 Python 3.3 起,这相当于 os.stat(fd) .

另请参阅

stat() 函数。

os. fstatvfs ( fd , / )

Return information about the filesystem containing the file associated with file descriptor fd ,像 statvfs() 。从 Python 3.3 起,这相当于 os.statvfs(fd) .

可用性 :Unix。

os. fsync ( fd )

强制写入文件采用文件描述符 fd 到磁盘。在 Unix,这调用本机 fsync() 函数;在 Windows,MS _commit() 函数。

若正开始采用缓冲 Python 文件对象 f ,首先做 f.flush() ,然后做 os.fsync(f.fileno()) ,以确保所有内部缓冲关联的 f 被写入磁盘。

可用性 :Unix、Windows。

os. ftruncate ( fd , length , / )

截取文件所对应的文件描述符 fd ,因此最多 length 字节按大小。从 Python 3.3 起,这相当于 os.truncate(fd, length) .

引发 审计事件 os.truncate 采用自变量 fd , length .

可用性 :Unix、Windows。

3.5 版改变: 添加支持 Windows

os. get_blocking ( fd , / )

获取文件描述符的阻塞模式: False O_NONBLOCK 标志有设置, True 若标志被清零。

另请参阅 set_blocking() and socket.socket.setblocking() .

可用性 :Unix。

函数在 Emscripten 和 WASI 是受限制,见 WebAssembly 平台 了解更多信息。

3.5 版新增。

os. isatty ( fd , / )

返回 True 若文件描述符 fd 被打开 且已连接到像 tty 设备,否则 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.

引发 审计事件 os.lockf 采用自变量 fd , cmd , len .

可用性 :Unix。

3.3 版新增。

os. F_LOCK
os. F_TLOCK
os. F_ULOCK
os. F_TEST

标志指定什么动作 lockf() 会接受。

可用性 :Unix。

3.3 版新增。

os. login_tty ( fd , / )

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.

可用性 :Unix,非 Emscripten,非 WASI。

3.11 版新增。

os. lseek ( fd , pos , how , / )

Set the current position of file descriptor fd to position pos , modified by how : SEEK_SET or 0 to set the position relative to the beginning of the file; SEEK_CUR or 1 to set it relative to the current position; 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

参数用于 lseek() 函数。它们的值分别为 0、1、和 2。

3.3 版新增: 某些操作系统可以支持额外值,像 os.SEEK_HOLE or os.SEEK_DATA .

os. open ( path , flags , mode = 0o777 , * , dir_fd = None )

打开文件 path 和设置各种标志根据 flags 且其模式可能根据 mode 。当计算 mode ,会先屏蔽掉当前 umask 值。返回新近打开文件的文件描述符。新文件描述符 不可继承 .

对于 flags 和 mode 值的描述,见 C 运行时文档编制;flags 常量 (像 O_RDONLY and O_WRONLY ) 的定义在 os 模块。尤其,在 Windows 添加 O_BINARY 需要以二进制模式打开文件。

此函数可以支持 相对于目录描述符的路径 采用 dir_fd 参数。

引发 审计事件 open 采用自变量 path , mode , flags .

3.4 版改变: 现在,新文件描述符不可继承。

注意

此函数旨在低级 I/O。对于正常用法,使用内置函数 open() ,其返回 文件对象 with read() and write() 方法 (及更多)。要包裹文件对象的文件描述符,使用 fdopen() .

3.3 版新增: dir_fd 自变量。

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,函数现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

3.6 版改变: 接受 像路径对象 .

下列常量是选项对于 flags 参数用于 open() 函数。可以组合它们使用按位 OR 运算符 | 。它们中的一些不可用于所有平台。对于它们的可用性和用法的描述,请翻阅 open(2) 手册页在 Unix 或 MSDN 在 Windows。

os. O_RDONLY
os. O_WRONLY
os. O_RDWR
os. O_APPEND
os. O_CREAT
os. O_EXCL
os. O_TRUNC

以上常量只可用于 Unix 和 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 版改变: 添加 O_CLOEXEC 常量。

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_EVTONLY
os. O_FSYNC
os. O_NOFOLLOW_ANY

以上常量只可用于 macOS。

3.10 版改变: 添加 O_EVTONLY , O_FSYNC , O_SYMLINK and O_NOFOLLOW_ANY 常量。

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

以上常量是扩展,且不存在若 C 库未定义它们。

3.4 版改变: 添加 O_PATH 在支持它的系统中。添加 O_TMPFILE ,只可用于 Linux 内核 3.11 或更高版本。

os. openpty ( )

打开新的伪终端对。返回一对文件描述符 (master, slave) for the pty and the tty, respectively. The new file descriptors are 不可继承 . For a (slightly) more portable approach, use the pty 模块。

可用性 :Unix,非 Emscripten,非 WASI。

3.4 版改变: 新文件描述符现在不可继承。

os. pipe ( )

创建管道。返回一对文件描述符 (r, w) 分别用于读取和写入。新文件描述符 不可继承 .

可用性 :Unix、Windows。

3.4 版改变: 新文件描述符现在不可继承。

os. pipe2 ( flags , / )

创建管道采用 flags 原子设置。 flags 可以被构造通过将这些值中的一个或多个 OR 到一起: O_NONBLOCK , O_CLOEXEC 。返回一对文件描述符 (r, w) usable for reading and writing, respectively.

可用性 :Unix,非 Emscripten,非 WASI。

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 字节。

可用性 :Unix、非 Emscripten。

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 起始于 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 .

可用性 :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() that specify the access pattern that is likely to be used.

可用性 :Unix。

3.3 版新增。

os. pread ( fd , n , offset , / )

读取最多 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.

可用性 :Unix。

3.3 版新增。

os. preadv ( fd , buffers , offset , flags = 0 , / )

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:

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.

Combine the functionality of os.readv() and os.pread() .

可用性 : Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.

Using flags requires Linux >= 4.6.

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 .

可用性 : Linux >= 4.14.

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 标志。

可用性 : Linux >= 4.6.

3.7 版新增。

os. pwrite ( fd , str , offset , / )

写入字节字符串按 str 到文件描述符 fd at position of offset , leaving the file offset unchanged.

返回实际写入的字节数。

可用性 :Unix。

3.3 版新增。

os. pwritev ( fd , buffers , offset , flags = 0 , / )

写入 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.

The flags argument contains a bitwise OR of zero or more of the following flags:

Return the total number of bytes actually written.

The operating system may set a limit ( sysconf() 'SC_IOV_MAX' ) on the number of buffers that can be used.

Combine the functionality of os.writev() and os.pwrite() .

可用性 : Linux >= 2.6.30, FreeBSD >= 6.0, OpenBSD >= 2.7, AIX >= 7.1.

Using flags requires Linux >= 4.6.

3.7 版新增。

os. RWF_DSYNC

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.

可用性 : Linux >= 4.7.

3.7 版新增。

os. RWF_SYNC

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.

可用性 : Linux >= 4.7.

3.7 版新增。

os. RWF_APPEND

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.

可用性 : Linux >= 4.16.

3.10 版新增。

os. read ( fd , n , / )

读取最多 n 字节从文件描述符 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.

注意

此函数旨在低级 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() 方法。

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,函数现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

os. sendfile ( out_fd , in_fd , offset , count )
os. sendfile ( out_fd , in_fd , offset , count , headers = () , trailers = () , flags = 0 )

拷贝 count 字节从文件描述符 in_fd 到文件描述符 out_fd 起始于 offset 。返回发送字节数。当到达 EOF (文件末尾) 时返回 0 .

第一函数表示法所有平台都支持,若平台有定义 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 自变量。

可用性 :Unix,非 Emscripten,非 WASI。

注意

对于高级包裹器 sendfile() ,见 socket.socket.sendfile() .

3.3 版新增。

3.9 版改变: 参数 out and in 被重命名为 out_fd and in_fd .

os. set_blocking ( fd , blocking , / )

设置指定文件描述符的阻塞模式。设置 O_NONBLOCK 标志若阻塞为 False ,否则清零标志。

另请参阅 get_blocking() and socket.socket.setblocking() .

可用性 :Unix。

函数在 Emscripten 和 WASI 是受限制,见 WebAssembly 平台 了解更多信息。

3.5 版新增。

os. SF_NODISKIO
os. SF_MNOWAIT
os. SF_SYNC

参数用于 sendfile() 函数,若实现支持它们。

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增。

os. SF_NOCACHE

参数用于 sendfile() function, if the implementation supports it. The data won’t be cached in the virtual memory and will be freed afterwards.

可用性 :Unix,非 Emscripten,非 WASI。

3.11 版新增。

os. splice ( src , dst , count , offset_src = None , offset_dst = None )

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, then 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 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

3.10 版新增。

os. SPLICE_F_MOVE
os. SPLICE_F_NONBLOCK
os. SPLICE_F_MORE

3.10 版新增。

os. readv ( fd , buffers , / )

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 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.

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

可用性 :Unix,非 WASI。

os. tcsetpgrp ( fd , pg , / )

Set the process group associated with the terminal given by fd (an open file descriptor as returned by os.open() ) 到 pg .

可用性 :Unix,非 WASI。

os. ttyname ( fd , / )

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.

可用性 :Unix。

os. write ( fd , str , / )

写入字节字符串按 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() 方法。

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,函数现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

os. writev ( fd , buffers , / )

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.

The operating system may set a limit ( sysconf() 'SC_IOV_MAX' ) on the number of buffers that can be used.

可用性 :Unix。

3.3 版新增。

查询终端的尺寸

3.3 版新增。

os. get_terminal_size ( fd = STDOUT_FILENO , / )

Return the size of the terminal window as (columns, lines) , tuple of type terminal_size .

可选自变量 fd (默认 STDOUT_FILENO , or standard output) specifies which file descriptor should be queried.

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.

可用性 :Unix、Windows。

class os. terminal_size

A subclass of tuple, holding (columns, lines) of the terminal window size.

columns

终端窗口的宽度 (以字符为单位)。

lines

终端窗口的高度 (以字符为单位)。

文件描述符的继承

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 .

在 WebAssembly 平台 wasm32-emscripten and wasm32-wasi , the file descriptor cannot be modified.

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).

可用性 :Windows。

os. set_handle_inheritable ( handle , inheritable , / )

Set the “inheritable” flag of the specified handle.

可用性 :Windows。

文件和目录

在某些 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 ).)

    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 .

    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 ).

    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. 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 应该为 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) 了解更多信息。

此函数可以支持指定 相对于目录描述符的路径 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() 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 参数。

3.6 版改变: 接受 像路径对象 .

os. F_OK
os. R_OK
os. W_OK
os. X_OK

值要传递作为 mode 参数对于 access() to test the existence, readability, writability and executability of path ,分别。

os. chdir ( path )

将当前工作目录更改成 path .

此函数可以支持 指定文件描述符 。描述符必须引用打开目录,而不是打开文件。

此函数可以引发 OSError 和子类譬如 FileNotFoundError , PermissionError ,和 NotADirectoryError .

引发 审计事件 os.chdir 采用自变量 path .

3.3 版新增: 添加支持指定 path 作为文件描述符在某些平台。

3.6 版改变: 接受 像路径对象 .

os. chflags ( path , flags , * , follow_symlinks = True )

设置标志为 path 到数值 flags . flags may take a combination (bitwise OR) of the following values (as defined in the stat 模块):

此函数可以支持 不遵循符号链接 .

引发 审计事件 os.chflags 采用自变量 path , flags .

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增: follow_symlinks 自变量。

3.6 版改变: 接受 像路径对象 .

os. chmod ( path , mode , * , dir_fd = None , follow_symlinks = True )

改变模式为 path 到数值 mode . mode may take one of the following values (as defined in the stat module) or bitwise ORed combinations of them:

此函数可以支持 指定文件描述符 , 相对于目录描述符的路径 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.

函数在 Emscripten 和 WASI 是受限制,见 WebAssembly 平台 了解更多信息。

引发 审计事件 os.chmod 采用自变量 path , mode , dir_fd .

3.3 版新增: 添加支持指定 path 按打开文件描述符,和 dir_fd and follow_symlinks 自变量。

3.6 版改变: 接受 像路径对象 .

os. chown ( path , uid , gid , * , dir_fd = None , follow_symlinks = True )

更改所有者和组 ID 为 path 到数值 uid and gid 。要使某一 ID 留下不变,将它设为 -1。

此函数可以支持 指定文件描述符 , 相对于目录描述符的路径 and 不遵循符号链接 .

shutil.chown() for a higher-level function that accepts names in addition to numeric ids.

引发 审计事件 os.chown 采用自变量 path , uid , gid , dir_fd .

可用性 :Unix。

函数在 Emscripten 和 WASI 是受限制,见 WebAssembly 平台 了解更多信息。

3.3 版新增: 添加支持指定 path 按打开文件描述符,和 dir_fd and follow_symlinks 自变量。

3.6 版改变: 支持 像路径对象 .

os. chroot ( path )

Change the root directory of the current process to path .

可用性 :Unix,非 Emscripten,非 WASI。

3.6 版改变: 接受 像路径对象 .

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) .

引发 审计事件 os.chdir 采用自变量 path .

可用性 :Unix。

os. getcwd ( )

返回当前工作目录的字符串表示。

os. getcwdb ( )

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.

os. lchflags ( path , flags )

设置标志为 path 到数值 flags ,像 chflags() , but do not follow symbolic links. As of Python 3.3, this is equivalent to os.chflags(path, flags, follow_symlinks=False) .

引发 审计事件 os.chflags 采用自变量 path , flags .

可用性 :Unix,非 Emscripten,非 WASI。

3.6 版改变: 接受 像路径对象 .

os. lchmod ( path , mode )

改变模式为 path 到数值 mode . If path is a symlink, this affects the symlink rather than the target. See the docs for chmod() 了解可能值对于 mode 。从 Python 3.3 起,这相当于 os.chmod(path, mode, follow_symlinks=False) .

引发 审计事件 os.chmod 采用自变量 path , mode , dir_fd .

可用性 :Unix。

3.6 版改变: 接受 像路径对象 .

os. lchown ( path , uid , gid )

更改所有者和组 ID 为 path 到数值 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) .

引发 审计事件 os.chown 采用自变量 path , uid , gid , dir_fd .

可用性 :Unix。

3.6 版改变: 接受 像路径对象 .

创建的硬链接指向 src 命名 dst .

此函数可以支持指定 src_dir_fd and/or dst_dir_fd 以提供 相对于目录描述符的路径 ,和 不遵循符号链接 .

引发 审计事件 os.link 采用自变量 src , dst , src_dir_fd , dst_dir_fd .

可用性 :Unix、Windows。

3.2 版改变: 添加 Windows 支持。

3.3 版新增: 添加 src_dir_fd , dst_dir_fd ,和 follow_symlinks 自变量。

3.6 版改变: 接受 像路径对象 for src and dst .

os. listdir ( path = '.' )

返回包含条目名称的列表,在给定目录 path 。列表采用任意次序,且不包括特殊条目 '.' and '..' 即使它们存在于目录中。若在此函数调用期间从目录移除文件 (或将文件添加目录),则是否包括该文件的名称未指定。

path 可以是 像路径对象 。若 path 是类型 bytes (直接或间接透过 PathLike 接口),返回文件名也会是类型 bytes ;在所有其它情况下,它们会是类型 str .

此函数还可以支持 指定文件描述符 ;文件描述符必须引用目录。

引发 审计事件 os.listdir 采用自变量 path .

注意

要编码 str 文件名成 bytes ,使用 fsencode() .

另请参阅

scandir() 函数返回目录条目及文件属性信息,为许多常见使用情况提供更优性能。

3.2 版改变: path 参数变为可选。

3.3 版新增: 添加支持指定 path 作为打开文件描述符。

3.6 版改变: 接受 像路径对象 .

os. lstat ( path , * , dir_fd = None )

履行等效 lstat() 系统调用按给定路径。类似 stat() ,但不遵循符号链接。返回 stat_result 对象。

在不支持符号链接的平台,这是别名化的 stat() .

从 Python 3.3 起,这相当于 os.stat(path, dir_fd=dir_fd, follow_symlinks=False) .

此函数还可以支持 相对于目录描述符的路径 .

另请参阅

stat() 函数。

3.2 版改变: 添加支持 Windows 6.0 (Vista) 符号链接。

3.3 版改变: 添加 dir_fd 参数。

3.6 版改变: 接受 像路径对象 .

3.8 版改变: 在 Windows,现在打开表示另一路径 (名称替代) 的重剖析点,包括符号链接和目录结。其它种类的重剖析点由操作系统解析,如对于 stat() .

os. mkdir ( path , mode = 0o777 , * , dir_fd = None )

创建目录命名 path 采用数值模式 mode .

若目录已存在, FileExistsError 被引发。若路径的父级目录不存在, FileNotFoundError 被引发。

在某些系统, mode 被忽略。若使用它,会先屏蔽掉当前 umask 值。若除了后 9 位 (即:以八进制表示后 3 位对于 mode ) 被设置,它们的含义从属平台。在某些平台,会忽略它们且应调用 chmod() 以明确设置它们。

此函数还可以支持 相对于目录描述符的路径 .

创建临时目录也是可能的;见 tempfile 模块的 tempfile.mkdtemp() 函数。

引发 审计事件 os.mkdir 采用自变量 path , mode , dir_fd .

3.3 版新增: dir_fd 自变量。

3.6 版改变: 接受 像路径对象 .

os. makedirs ( name , mode = 0o777 , exist_ok = False )

递归目录创建函数。像 mkdir() ,但生成需要包含叶目录的所有中间级目录。

mode 参数会被传递给 mkdir() 用于创建叶目录;见 mkdir() 描述 了解它是如何被解释的。要设置任何新近创建的父级目录下的文件权限位,可以设置 umask 先于援引 makedirs() 。现有父级目录的文件权限位不改变。

exist_ok is False (默认), FileExistsError 被引发若目标目录已存在。

注意

makedirs() 会变得困惑若要创建的路径元素包含 pardir (如 .. 在 Unix 系统)。

此函数正确处理 UNC 路径。

引发 审计事件 os.mkdir 采用自变量 path , mode , dir_fd .

3.2 版新增: exist_ok 参数。

3.4.1 版改变: 在 Python 3.4.1 之前,若 exist_ok was True 且目录存在, makedirs() 仍将引发错误若 mode 不匹配现有目录模式。由于这种行为不可能安全实现,因此 Python 3.4.1 已将它移除。见 bpo-21082 .

3.6 版改变: 接受 像路径对象 .

3.7 版改变: mode 自变量不再影响新近创建的中间级目录的文件权限位。

os. mkfifo ( path , mode = 0o666 , * , dir_fd = None )

创建 FIFO (命名管道) 命名 path 采用数值模式 mode 。首先从 mode 屏蔽掉当前 umask 值。

此函数还可以支持 相对于目录描述符的路径 .

FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with 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() doesn’t open the FIFO — it just creates the rendezvous point.

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增: dir_fd 自变量。

3.6 版改变: 接受 像路径对象 .

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 ,和 stat.S_IFIFO (those constants are available in stat ). For stat.S_IFCHR and stat.S_IFBLK , device defines the newly created device special file (probably using os.makedev() ),否则被忽略。

此函数还可以支持 相对于目录描述符的路径 .

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增: dir_fd 自变量。

3.6 版改变: 接受 像路径对象 .

os. major ( device , / )

Extract the device major number from a raw device number (usually the st_dev or st_rdev 字段来自 stat ).

os. minor ( device , / )

Extract the device minor number from a raw device number (usually the st_dev or st_rdev 字段来自 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.

name 是字符串且未知, ValueError 被引发。若特定值对于 name 主机系统不支持,即使包括在 pathconf_names OSError 被引发采用 errno.EINVAL 对于错误编号。

此函数可以支持 指定文件描述符 .

可用性 :Unix。

3.6 版改变: 接受 像路径对象 .

os. pathconf_names

字典映射的名称接受通过 pathconf() and 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.

可用性 :Unix。

返回符号链接指向路径的表示字符串。结果可能是绝对 (或相对) 路径名;若是相对的,可以将它转换成绝对路径名使用 os.path.join(os.path.dirname(path), result) .

path is a string object (directly or indirectly through a 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.

此函数还可以支持 相对于目录描述符的路径 .

当试着解析可能包含链接的路径时,使用 realpath() 以正确处理递归和平台差异。

可用性 :Unix、Windows。

3.2 版改变: 添加支持 Windows 6.0 (Vista) 符号链接。

3.3 版新增: dir_fd 自变量。

3.6 版改变: 接受 像路径对象 在 Unix。

3.8 版改变: 接受 像路径对象 和 bytes 对象在 Windows。

3.8 版改变: Added support for directory junctions, and changed to return the substitution path (which typically includes \\?\ prefix) rather than the optional “print name” field that was previously returned.

os. remove ( path , * , dir_fd = None )

移除 (删除) 文件 path 。若 path 是目录, IsADirectoryError 被引发。使用 rmdir() 能移除目录。若文件不存在, FileNotFoundError 被引发。

此函数可以支持 相对于目录描述符的路径 .

在 Windows,试图移除使用中的文件会导致引发异常;在 Unix,目录条目被移除,但分配给文件的存储不可用,直到原始文件不再在使用中为止。

此函数在语义上等同于 unlink() .

引发 审计事件 os.remove 采用自变量 path , dir_fd .

3.3 版新增: dir_fd 自变量。

3.6 版改变: 接受 像路径对象 .

os. removedirs ( name )

递归移除目录。工作像 rmdir() 除若成功移除叶目录外, removedirs() 会试着依次移除提及的每个父级目录在 path 直到引发错误 (被忽略,因为通常意味着父级目录非空)。例如, os.removedirs('foo/bar/baz') 会先移除目录 'foo/bar/baz' ,然后移除 'foo/bar' and 'foo' 若它们为空。引发 OSError 若无法成功移除叶目录。

引发 审计事件 os.remove 采用自变量 path , dir_fd .

3.6 版改变: 接受 像路径对象 .

os. rename ( src , dst , * , src_dir_fd = None , dst_dir_fd = None )

重命名文件或目录 src to dst 。若 dst 存在,操作将失败按 OSError 子类在很多情况下:

在 Windows,若 dst 存在 FileExistsError 始终被引发。

在 Unix,若 src 是文件和 dst 是目录或反之亦然, IsADirectoryError NotADirectoryError 会被分别引发。若两者是目录且 dst 为空, dst 将被默默替换。若 dst 是非空目录, OSError 被引发。若两者是文件, dst will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst 在不同文件系统。若成功,重命名将是原子操作 (这是 POSIX 要求的)。

此函数可以支持指定 src_dir_fd and/or dst_dir_fd 以提供 相对于目录描述符的路径 .

若想要跨平台覆写目的地,使用 replace() .

引发 审计事件 os.rename 采用自变量 src , dst , src_dir_fd , dst_dir_fd .

3.3 版新增: src_dir_fd and dst_dir_fd 自变量。

3.6 版改变: 接受 像路径对象 for src and dst .

os. renames ( old , new )

目录 (或文件) 递归重命名函数。工作像 rename() ,除首先会试图创建使新路径名工作良好所需的任何中间体目录外。重命名后,会修剪掉旧名称最右路径段的对应目录使用 removedirs() .

注意

此函数创建新目录结构时可能失败,若缺乏移除叶目录 (或文件) 所需的权限。

引发 审计事件 os.rename 采用自变量 src , dst , src_dir_fd , dst_dir_fd .

3.6 版改变: 接受 像路径对象 for old and new .

os. replace ( src , dst , * , src_dir_fd = None , dst_dir_fd = None )

重命名文件或目录 src to dst 。若 dst 是非空目录, OSError 会被引发。若 dst 存在且是文件,会默默替换它若用户拥有权限。操作可能失败若 src and dst 在不同文件系统。若成功,重命名将是原子操作 (这是 POSIX 要求的)。

此函数可以支持指定 src_dir_fd and/or dst_dir_fd 以提供 相对于目录描述符的路径 .

引发 审计事件 os.rename 采用自变量 src , dst , src_dir_fd , dst_dir_fd .

3.3 版新增。

3.6 版改变: 接受 像路径对象 for src and dst .

os. rmdir ( path , * , dir_fd = None )

移除 (删除) 目录 path 。若目录不存在或非空, FileNotFoundError OSError 被分别引发。为移除整个目录树, shutil.rmtree() 可以使用。

此函数可以支持 相对于目录描述符的路径 .

引发 审计事件 os.rmdir 采用自变量 path , dir_fd .

3.3 版新增: dir_fd 参数。

3.6 版改变: 接受 像路径对象 .

os. scandir ( path = '.' )

返回迭代器为 os.DirEntry 对象,对应目录中的条目给出通过 path 。产生条目的次序是任意的,且特殊条目 '.' and '..' 未包括在内。若创建迭代器之后从目录移除文件或将文件添加到目录,未指定是否包括该文件条目。

使用 scandir() 而不是 listdir() 可以显著提高还需要文件类型 (或文件属性) 信息的代码性能,因为 os.DirEntry 对象曝光此信息若操作系统在扫描目录时提供。所有 os.DirEntry 方法可以履行系统调用,但 is_dir() and is_file() 通常只要求系统调用符号链接; os.DirEntry.stat() 在 Unix 始终要求系统调用,但在 Windows 只要求一符号链接。

path 可以是 像路径对象 。若 path 是类型 bytes (直接或间接透过 PathLike 接口),类型的 name and path 属性在各 os.DirEntry 将是 bytes ;在所有其它情况下,它们会是类型 str .

此函数还可以支持 指定文件描述符 ;文件描述符必须引用目录。

引发 审计事件 os.scandir 采用自变量 path .

scandir() 迭代器支持 上下文管理器 协议,且拥有下列方法:

scandir. close ( )

关闭迭代器并释放获得的资源。

会自动调用这当迭代器被耗尽或被垃圾收集时,或在迭代期间发生错误时。不管怎样,建议明确调用它或使用 with 语句。

3.6 版新增。

以下范例展示简单使用 scandir() 来显示所有文件 (不包括目录) 以给定 path 开头不采用 '.' entry.is_file() 调用通常不做额外系统调用:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
								

注意

在基于 Unix 的系统, scandir() 使用系统的 opendir() and readdir() 函数。在 Windows,它使用 Win32 FindFirstFileW and FindNextFileW 函数。

3.5 版新增。

3.6 版新增: 添加支持 上下文管理器 协议和 close() 方法。若 scandir() 迭代器既未耗尽,也未明确关闭 ResourceWarning 将在其析构函数中被发射。

函数接受 像路径对象 .

3.7 版改变: 添加支持 file descriptors 在 Unix。

class os. DirEntry

对象的产生通过 scandir() 来暴露目录条目的文件路径及其它文件属性。

scandir() 将尽可能多的提供这种信息,无需做出额外系统调用。当 stat() or lstat() 系统调用做出时, os.DirEntry 对象会缓存结果。

os.DirEntry 实例不打算存储长期存活数据结构;若知道文件元数据已改变,或已消耗很长时间从调用 scandir() ,调用 os.stat(entry.path) 以抓取最新信息。

由于 os.DirEntry 方法可以做操作系统调用,它们还可能引发 OSError 。若需要很细粒度的错误控制,可以捕获 OSError 当调用某一 os.DirEntry 方法和适当处理时。

可直接用作 像路径对象 , os.DirEntry 实现 PathLike 接口。

属性和方法在 os.DirEntry 实例如下:

name

条目的基本文件名,相对于 scandir() path 自变量。

name 属性将是 bytes scandir() path 自变量是类型 bytes and str 否则。使用 fsdecode() 以解码字节文件名。

path

条目的完整路径名:相当于 os.path.join(scandir_path, entry.name) where scandir_path scandir() path 自变量。路径才是绝对的若 scandir() path 自变量是绝对路径。若 scandir() path 自变量是 文件描述符 path 属性如同 name 属性。

path 属性将是 bytes scandir() path 自变量是类型 bytes and str 否则。使用 fsdecode() 以解码字节文件名。

inode ( )

返回条目的 Inode 编号。

结果被缓存在 os.DirEntry 对象。使用 os.stat(entry.path, follow_symlinks=False).st_ino 以抓取最新信息。

当首次不缓存调用,在 Windows 要求系统调用,但在 Unix 不要求。

is_dir ( * , follow_symlinks = True )

返回 True 若此条目是目录 (或指向目录的符号链接);返回 False 若条目是 (或是) 指向任何其它种类的文件,或者若它不再存在。

follow_symlinks is False ,返回 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.

结果被缓存在 os.DirEntry 对象,提供单独缓存为 follow_symlinks True and False 。调用 os.stat() along with stat.S_ISDIR() 以抓取最新信息。

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 .

此方法可以引发 OSError ,譬如 PermissionError ,但 FileNotFoundError 会被捕获但不引发。

is_file ( * , follow_symlinks = True )

返回 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.

follow_symlinks is False ,返回 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.

结果被缓存在 os.DirEntry object. Caching, system calls made, and exceptions raised are as per is_dir() .

返回 True 若此条目是符号链接 (即使中断);返回 False if the entry points to a directory or any kind of file, or if it doesn’t exist anymore.

结果被缓存在 os.DirEntry 对象。调用 os.path.islink() 以抓取最新信息。

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 .

此方法可以引发 OSError ,譬如 PermissionError ,但 FileNotFoundError 会被捕获但不引发。

stat ( * , follow_symlinks = True )

返回 stat_result 对象为此条目。此方法遵循符号链接,默认情况下;要统计符号链接,添加 follow_symlinks=False 自变量。

在 Unix,此方法始终要求系统调用。在 Windows,它才要求系统调用若 follow_symlinks is True 且条目是重剖析点 (例如:符号链接或目录结点)。

在 Windows, st_ino , st_dev and st_nlink 属性对于 stat_result 始终被设为 0。调用 os.stat() 以获取这些属性。

结果被缓存在 os.DirEntry 对象,提供单独缓存为 follow_symlinks True and False 。调用 os.stat() 以抓取最新信息。

注意,存在很好的对应在几个属性和方法方面对于 os.DirEntry 和对于 pathlib.Path 。尤其, name 属性拥有相同含义,如 is_dir() , is_file() , is_symlink() and stat() 方法。

3.5 版新增。

3.6 版改变: 添加支持 PathLike 接口。添加支持 bytes 路径在 Windows。

os. stat ( path , * , dir_fd = None , follow_symlinks = True )

获取文件或文件描述符的状态。履行等效 stat() 系统调用按给定路径。 path 可以指定作为字符串或 bytes – 直接或间接透过 PathLike 接口 – 或作为打开文件描述符。返回 stat_result 对象。

此函数通常遵循符号链接。要统计符号链接,添加自变量 follow_symlinks=False ,或使用 lstat() .

此函数可以支持 指定文件描述符 and 不遵循符号链接 .

在 Windows,传递 follow_symlinks=False 将禁用遵循所有名称代理的重剖析点,包括符号链接和目录结。不像链接 (或操作系统无法追踪) 的其它类型的重解析点,会被直接打开。当遵循多个链接的链时,这可能导致返回原始链接,而不是阻止完整遍历的非链接。在这种情况下,要获取最终路径的 stat (统计) 结果,使用 os.path.realpath() 函数以尽可能解析路径名和调用 lstat() 在结果。这不适用于悬空符号链接或结合点,通常会引发异常。

范例:

>>> 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() and lstat() 函数。

3.3 版新增: 添加 dir_fd and follow_symlinks 自变量,指定文件描述符而不是路径。

3.6 版改变: 接受 像路径对象 .

3.8 版改变: 在 Windows,所有可以被操作系统解析的重剖析点现在都被遵循,且传递 follow_symlinks=False 将禁用遵循所有名称代理重剖析点。若操作系统到达无法遵循的重剖析点, stat 现在返回原始路径信息,就像 follow_symlinks=False 有指定,而不是引发错误。

class os. stat_result

属性大致相当于成员的对象对于 stat 结构。用于结果在 os.stat() , os.fstat() and os.lstat() .

属性:

st_mode

文件模式:文件类型和文件模式 (权限) 位。

st_ino

从属平台,但若非 0,唯一标识文件为给定值的 st_dev 。通常:

st_dev

此文件所在设备的标识符。

硬链接数。

st_uid

文件所有者的用户标识符。

st_gid

文件所有者的组标识符。

st_size

文件大小 (以字节为单位),若是常规文件或符号链接。符号链接大小是它所包含的路径名长度,不包含终止 null 字节。

时间戳:

st_atime

最近访问时间 (以秒为单位表达)。

st_mtime

最近内容修改时间 (以秒为单位表达)。

st_ctime

从属平台:

  • 在 Unix 是最近元数据更改时间,

  • 在 Windows 是创建时间 (以秒为单位表达)。

st_atime_ns

以整数形式表达的最近访问时间,以纳秒为单位。

st_mtime_ns

整数以纳秒为单位表达的最近修改内容的时间。

st_ctime_ns

从属平台:

  • 在 Unix 是最近元数据更改时间,

  • 整数以纳秒为单位表达的 Windows 创建时间。

注意

准确含义和分辨率对于 st_atime , st_mtime ,和 st_ctime 属性从属操作系统和文件系统。例如,Windows 系统使用 FAT (或 FAT32) 文件系统, st_mtime 拥有 2 秒分辨率,和 st_atime 只有 1 天的分辨率。见操作系统文档编制了解细节。

同样,尽管 st_atime_ns , st_mtime_ns ,和 st_ctime_ns 始终以纳秒为单位表达,但很多系统不提供纳秒精度。在提供纳秒精度的系统,使用浮点对象存储 st_atime , st_mtime ,和 st_ctime 无法保留它的所有,因此有点不准确。若需要准确时间戳,应始终使用 st_atime_ns , st_mtime_ns ,和 st_ctime_ns .

在某些 Unix 系统 (譬如 Linux),下列属性也可能可用:

st_blocks

为文件分配的 512 字节块的数量。这可能小于 st_size /512 当文件有空穴时。

st_blksize

用于高效文件系统 I/O 的 "首选" 块大小。以较小分块方式写入文件,可能导致低效读取-修改-重写。

st_rdev

设备类型若是 Inode 设备。

st_flags

用户为文件定义的标志。

在其它 Unix 系统 (譬如 FreeBSD),下列属性可能可用 (但可能才填写当 root 试着使用它们时):

st_gen

文件生成编号。

st_birthtime

文件创建的时间。

在 Solaris 及其衍生,下列属性也可能可用:

st_fstype

包含文件的文件系统类型的唯一标识字符串。

在 macOS 系统,下列属性也可能可用:

st_rsize

文件的实际大小。

st_creator

文件的创建者。

st_type

文件类型。

在 Windows 系统,下列属性也可用:

st_file_attributes

Windows 文件属性: dwFileAttributes 成员对于 BY_HANDLE_FILE_INFORMATION 结构返回通过 GetFileInformationByHandle() 。见 FILE_ATTRIBUTE_* 常量在 stat 模块。

st_reparse_tag

st_file_attributes 拥有 FILE_ATTRIBUTE_REPARSE_POINT 设置,此字段包含标识重剖析点类型的标记。见 IO_REPARSE_TAG_* 常量在 stat 模块。

标准模块 stat 定义的函数和常量很有用为提取信息从 stat 结构 (在 Windows,某些项以虚设值填充)。

为向后兼容, stat_result 实例也可以按至少 10 整数元组形式访问,给出最重要 (且可移植) 成员对于 stat 结构,按次序 st_mode , st_ino , st_dev , st_nlink , st_uid , st_gid , st_size , st_atime , st_mtime , st_ctime 。某些实现可能在结尾添加更多项。为兼容旧版 Python,访问 stat_result 以元组形式始终返回整数。

3.3 版新增: 添加 st_atime_ns , st_mtime_ns ,和 st_ctime_ns 成员。

3.5 版新增: 添加 st_file_attributes 成员在 Windows。

3.5 版改变: Windows 现在将文件索引返回作为 st_ino 当可用时。

3.7 版新增: 添加 st_fstype 成员到 Solaris/衍生。

3.8 版新增: 添加 st_reparse_tag 成员在 Windows。

3.8 版改变: 在 Windows, st_mode 成员现在将特殊文件标识为 S_IFCHR , S_IFIFO or S_IFBLK 酌情。

os. statvfs ( path )

履行 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 (禁止程序执行), ST_SYNCHRONOUS (writes are synced at once), ST_MANDLOCK (allow mandatory locks on an FS), ST_WRITE (write on file/directory/symlink), ST_APPEND (仅追加文件), ST_IMMUTABLE (不可变文件), ST_NOATIME (不更新访问时间), ST_NODIRATIME (不更新目录访问时间), ST_RELATIME (相对 mtime/ctime 更新 atime)。

此函数可以支持 指定文件描述符 .

可用性 :Unix。

3.2 版改变: ST_RDONLY and ST_NOSUID 常量被添加。

3.3 版新增: 添加支持指定 path 作为打开文件描述符。

3.4 版改变: ST_NODEV , ST_NOEXEC , ST_SYNCHRONOUS , ST_MANDLOCK , ST_WRITE , ST_APPEND , ST_IMMUTABLE , ST_NOATIME , ST_NODIRATIME ,和 ST_RELATIME 常量被添加。

3.6 版改变: 接受 像路径对象 .

3.7 版新增: 添加 f_fsid .

os. supports_dir_fd

A set object indicating which functions in the os module accept an open file descriptor for their dir_fd parameter. Different platforms provide different features, and the underlying functionality Python uses to implement the dir_fd parameter is not available on all platforms Python supports. For consistency’s sake, functions that may support dir_fd always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying None for dir_fd is always supported on all platforms.)

To check whether a particular function accepts an open file descriptor for its dir_fd parameter, use the in operator on supports_dir_fd . As an example, this expression evaluates to True if os.stat() accepts open file descriptors for dir_fd on the local platform:

os.stat in os.supports_dir_fd
							

目前 dir_fd parameters only work on Unix platforms; none of them work on Windows.

3.3 版新增。

os. supports_effective_ids

A set object indicating whether os.access() permits specifying True for its effective_ids parameter on the local platform. (Specifying False for effective_ids is always supported on all platforms.) If the local platform supports it, the collection will contain os.access() ; otherwise it will be empty.

This expression evaluates to True if os.access() supports effective_ids=True on the local platform:

os.access in os.supports_effective_ids
							

目前 effective_ids is only supported on Unix platforms; it does not work on Windows.

3.3 版新增。

os. supports_fd

A set object indicating which functions in the os module permit specifying their path parameter as an open file descriptor on the local platform. Different platforms provide different features, and the underlying functionality Python uses to accept open file descriptors as path arguments is not available on all platforms Python supports.

To determine 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 evaluates to True if os.chdir() accepts open file descriptors for path on your local platform:

os.chdir in os.supports_fd
							

3.3 版新增。

A set object indicating which functions in the os module accept False for their follow_symlinks parameter on the local platform. Different platforms provide different features, and the underlying functionality Python uses to implement follow_symlinks is not available on all platforms Python supports. For consistency’s sake, functions that may support follow_symlinks always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying True for follow_symlinks is always supported on all platforms.)

To check whether a particular function accepts False for its follow_symlinks parameter, use the in operator on supports_follow_symlinks . As an example, this expression evaluates to True if you may specify follow_symlinks=False 当调用 os.stat() on the local platform:

os.stat in os.supports_follow_symlinks
							

3.3 版新增。

创建的符号链接指向 src 命名 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 被忽略。

此函数可以支持 相对于目录描述符的路径 .

注意

On newer versions of Windows 10, unprivileged accounts can create symlinks if Developer Mode is enabled. When Developer Mode is not available/enabled, the SeCreateSymbolicLinkPrivilege privilege is required, or the process must be run as an administrator.

OSError is raised when the function is called by an unprivileged user.

引发 审计事件 os.symlink 采用自变量 src , dst , dir_fd .

可用性 :Unix、Windows。

函数在 Emscripten 和 WASI 是受限制,见 WebAssembly 平台 了解更多信息。

3.2 版改变: 添加支持 Windows 6.0 (Vista) 符号链接。

3.3 版新增: 添加 dir_fd argument, and now allow target_is_directory on non-Windows platforms.

3.6 版改变: 接受 像路径对象 for src and dst .

3.8 版改变: Added support for unelevated symlinks on Windows with Developer Mode.

os. sync ( )

强制将所有事情写入磁盘。

可用性 :Unix。

3.3 版新增。

os. truncate ( path , length )

截取文件所对应的 path ,因此最多 length 字节大小。

此函数可以支持 指定文件描述符 .

引发 审计事件 os.truncate 采用自变量 path , length .

可用性 :Unix、Windows。

3.3 版新增。

3.5 版改变: 添加支持 Windows

3.6 版改变: 接受 像路径对象 .

移除 (删除) 文件 path 。此函数在语义上等同于 remove() unlink 名称是它的传统 Unix 名称。请参阅文档编制为 remove() 了解进一步信息。

引发 审计事件 os.remove 采用自变量 path , dir_fd .

3.3 版新增: dir_fd 参数。

3.6 版改变: 接受 像路径对象 .

os. utime ( path , times=None , * , [ ns , ] dir_fd=None , follow_symlinks=True )

设置文件的访问和修改时间指定通过 path .

utime() 接受 2 可选参数 times and ns 。这些指定设置时间在 path 且用法如下:

  • ns 有指定,它必须是 2 元素元组形式 (atime_ns, mtime_ns) 各成员是表达纳秒的 int。

  • times 不是 None ,它必须是 2 元素元组形式 (atime, mtime) 各成员是表达秒数的 int 或浮点。

  • times is None and ns 未指定,这相当于指定 ns=(atime_ns, mtime_ns) 2 时间是当前时间。

指定元组是错误的对于两 times and ns .

注意,在这里设置的准确时间可能不会被返回通过后续 stat() 调用,从属操作系统记录访问时间和修改时间的分辨率; 见 stat() 。保留准确时间的最佳方式是使用 st_atime_ns and st_mtime_ns 字段来自 os.stat() 结果对象采用 ns 参数用于 utime() .

此函数可以支持 指定文件描述符 , 相对于目录描述符的路径 and 不遵循符号链接 .

引发 审计事件 os.utime 采用自变量 path , times , ns , dir_fd .

3.3 版新增: 添加支持指定 path 按打开文件描述符,和 dir_fd , follow_symlinks ,和 ns 参数。

3.6 版改变: 接受 像路径对象 .

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 本身),它产生 3 元组 (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) . Whether or not the lists are sorted depends on the file system. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified.

若可选自变量 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.

topdown is True , the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and 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() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames 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() call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, an 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.

默认情况下, 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() 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() . 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() ), walking the tree bottom-up is essential, 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))
							

引发 审计事件 os.walk 采用自变量 top , topdown , onerror , followlinks .

3.5 版改变: 此函数现在调用 os.scandir() 而不是 os.listdir() ,使之更快通过减少调用数为 os.stat() .

3.6 版改变: 接受 像路径对象 .

os. fwalk ( top = '.' , topdown = True , onerror = None , * , follow_symlinks = False , dir_fd = None )

此行为准确像 walk() , except that it yields a 4-tuple (dirpath, dirnames, filenames, dirfd) ,且它支持 dir_fd .

dirpath , dirnames and filenames are identical to walk() output, and dirfd is a file descriptor referring to the directory dirpath .

This function always supports 相对于目录描述符的路径 and 不遵循符号链接 . Note however that, unlike other functions, the fwalk() 默认值为 follow_symlinks is False .

注意

由于 fwalk() yields file descriptors, those are only valid until the next iteration step, so you should duplicate them (e.g. with 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() 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)
							

引发 审计事件 os.fwalk 采用自变量 top , topdown , onerror , follow_symlinks , dir_fd .

可用性 :Unix。

3.3 版新增。

3.6 版改变: 接受 像路径对象 .

3.7 版改变: 添加支持 bytes paths.

os. memfd_create ( name [ , flags=os.MFD_CLOEXEC ] )

Create an anonymous file and return a file descriptor that refers to it. flags 必须是某一 os.MFD_* constants available on the system (or a bitwise ORed combination of them). By default, the new file descriptor is 不可继承 .

The name supplied in name is used as a filename and will be displayed as the target of the corresponding symbolic link in the directory /proc/self/fd/ . The displayed name is always prefixed with memfd: and serves only for debugging purposes. Names do not affect the behavior of the file descriptor, and as such multiple files can have the same name without any side effects.

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

3.8 版新增。

os. MFD_CLOEXEC
os. MFD_ALLOW_SEALING
os. MFD_HUGETLB
os. MFD_HUGE_SHIFT
os. MFD_HUGE_MASK
os. MFD_HUGE_64KB
os. MFD_HUGE_512KB
os. MFD_HUGE_1MB
os. MFD_HUGE_2MB
os. MFD_HUGE_8MB
os. MFD_HUGE_16MB
os. MFD_HUGE_32MB
os. MFD_HUGE_256MB
os. MFD_HUGE_512MB
os. MFD_HUGE_1GB
os. MFD_HUGE_2GB
os. MFD_HUGE_16GB

这些标志可以传递给 memfd_create() .

可用性 : Linux >= 3.17 with glibc >= 2.27

MFD_HUGE* 标志才可用从 Linux 4.14 起。

3.8 版新增。

os. eventfd ( initval [ , flags=os.EFD_CLOEXEC ] )

Create and return an event file descriptor. The file descriptors supports raw read() and write() with a buffer size of 8, select() , poll() and similar. See man page eventfd(2) for more information. By default, the new file descriptor is 不可继承 .

initval is the initial value of the event counter. The initial value must be an 32 bit unsigned integer. Please note that the initial value is limited to a 32 bit unsigned int although the event counter is an unsigned 64 bit integer with a maximum value of 2 64 -2.

flags can be constructed from EFD_CLOEXEC , EFD_NONBLOCK ,和 EFD_SEMAPHORE .

EFD_SEMAPHORE is specified and the event counter is non-zero, eventfd_read() returns 1 and decrements the counter by one.

EFD_SEMAPHORE is not specified and the event counter is non-zero, eventfd_read() returns the current event counter value and resets the counter to zero.

If the event counter is zero and EFD_NONBLOCK 未指定, eventfd_read() blocks.

eventfd_write() increments the event counter. Write blocks if the write operation would increment the counter to a value larger than 2 64 -2.

范例:

import os
# semaphore with start value '1'
fd = os.eventfd(1, os.EFD_SEMAPHORE | os.EFC_CLOEXEC)
try:
    # acquire semaphore
    v = os.eventfd_read(fd)
    try:
        do_work()
    finally:
        # release semaphore
        os.eventfd_write(fd, v)
finally:
    os.close(fd)
								

可用性 : Linux >= 2.6.27 with glibc >= 2.8

3.10 版新增。

os. eventfd_read ( fd )

Read value from an eventfd() file descriptor and return a 64 bit unsigned int. The function does not verify that fd eventfd() .

可用性 : Linux >= 2.6.27

3.10 版新增。

os. eventfd_write ( fd , value )

Add value to an eventfd() file descriptor. value must be a 64 bit unsigned int. The function does not verify that fd eventfd() .

可用性 : Linux >= 2.6.27

3.10 版新增。

os. EFD_CLOEXEC

Set close-on-exec flag for new eventfd() file descriptor.

可用性 : Linux >= 2.6.27

3.10 版新增。

os. EFD_NONBLOCK

Set O_NONBLOCK status flag for new eventfd() file descriptor.

可用性 : Linux >= 2.6.27

3.10 版新增。

os. EFD_SEMAPHORE

Provide semaphore-like semantics for reads from a eventfd() file descriptor. On read the internal counter is decremented by one.

可用性 : Linux >= 2.6.30

3.10 版新增。

Linux 扩展属性

3.3 版新增。

这些函数只可用于 Linux。

os. getxattr ( path , 属性 , * , follow_symlinks = True )

Return the value of the extended filesystem attribute 属性 for path . 属性 can be bytes or str (directly or indirectly through the PathLike interface). If it is str, it is encoded with the filesystem encoding.

此函数可以支持 指定文件描述符 and 不遵循符号链接 .

引发 审计事件 os.getxattr 采用自变量 path , attribute .

3.6 版改变: 接受 像路径对象 for path and 属性 .

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() will examine the current directory.

此函数可以支持 指定文件描述符 and 不遵循符号链接 .

引发 审计事件 os.listxattr 采用自变量 path .

3.6 版改变: 接受 像路径对象 .

os. removexattr ( path , 属性 , * , follow_symlinks = True )

Removes the extended filesystem attribute 属性 from path . 属性 should be bytes or str (directly or indirectly through the PathLike interface). If it is a string, it is encoded with the 文件系统编码和错误处理程序 .

此函数可以支持 指定文件描述符 and 不遵循符号链接 .

引发 审计事件 os.removexattr 采用自变量 path , attribute .

3.6 版改变: 接受 像路径对象 for path and 属性 .

os. setxattr ( path , 属性 , value , flags = 0 , * , follow_symlinks = True )

Set the extended filesystem attribute 属性 on path to value . 属性 must be a bytes or str with no embedded NULs (directly or indirectly through the PathLike interface). If it is a str, it is encoded with the 文件系统编码和错误处理程序 . flags 可以是 XATTR_REPLACE or XATTR_CREATE 。若 XATTR_REPLACE is given and the attribute does not exist, ENODATA 会被引发。若 XATTR_CREATE is given and the attribute already exists, the attribute will not be created and EEXISTS 会被引发。

此函数可以支持 指定文件描述符 and 不遵循符号链接 .

注意

A bug in Linux kernel versions less than 2.6.39 caused the flags argument to be ignored on some filesystems.

引发 审计事件 os.setxattr 采用自变量 path , attribute , value , flags .

3.6 版改变: 接受 像路径对象 for path and 属性 .

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() . It indicates the operation must create an attribute.

os. XATTR_REPLACE

This is a possible value for the flags argument in setxattr() . It indicates the operation must replace an existing attribute.

进程管理

这些函数可用于创建和管理进程。

The various exec* 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() 。例如, os.execv('/bin/echo', ['foo', 'bar']) 只会打印 bar on standard output; foo will seem to be ignored.

os. abort ( )

生成 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() .

os. add_dll_directory ( path )

将路径添加到 DLL 搜索路径。

This search path is used when resolving dependencies for imported extension modules (the module itself is resolved through sys.path ), and also by ctypes .

移除目录通过调用 close() 在返回对象或使用它在 with 语句。

微软文档编制 了解如何加载 DLL 的更多有关信息。

引发 审计事件 os.add_dll_directory 采用自变量 path .

可用性 :Windows。

3.8 版新增: 先前版本的 CPython 使用当前进程的默认行为解析 DLL。这会导致不一致,譬如有时仅搜索 PATH 或当前工作目录,且 OS 函数譬如 AddDllDirectory 不起作用。

从 3.8 起,加载 DLL 的 2 种首要方式现在是明确覆盖进程范围行为以确保一致性。见 移植说明 了解更新库的有关信息。

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 异常。

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() before calling an exec* 函数。

The “l” and “v” variants of the exec* 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() , execlpe() , execvp() ,和 execvpe() ) 将使用 PATH environment variable to locate the program file . When the environment is being replaced (using one of the exec*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, execl() , execle() , execv() ,和 execve() , will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path.

For execle() , execlpe() , execve() ,和 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() , execlp() , execv() ,和 execvp() all cause the new process to inherit the environment of the current process.

For 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 . If it is unavailable, using it will raise a NotImplementedError .

引发 审计事件 os.exec 采用自变量 path , args , env .

可用性 :Unix、Windows、非 Emscripten、非 WASI。

3.3 版新增: 添加支持指定 path 作为打开文件描述符对于 execve() .

3.6 版改变: 接受 像路径对象 .

os. _exit ( n )

退出进程采用状态 n ,不调用清理处理程序、刷新 stdio 缓冲、等。

注意

退出的标准方式为 sys.exit(n) . _exit() should normally only be used in the child process after a fork() .

The following exit codes are defined and can be used with _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. May be taken from the defined value of EXIT_SUCCESS on some platforms. Generally has a value of zero.

可用性 :Unix、Windows。

os. EX_USAGE

Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_DATAERR

意味着输入数据不正确的退出代码。

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_NOINPUT

Exit code that means an input file did not exist or was not readable.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_NOUSER

Exit code that means a specified user did not exist.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_NOHOST

Exit code that means a specified host did not exist.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_UNAVAILABLE

Exit code that means that a required service is unavailable.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_SOFTWARE

Exit code that means an internal software error was detected.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_OSERR

Exit code that means an operating system error was detected, such as the inability to fork or create a pipe.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_OSFILE

Exit code that means some system file did not exist, could not be opened, or had some other kind of error.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_CANTCREAT

Exit code that means a user specified output file could not be created.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_IOERR

Exit code that means that an error occurred while doing I/O on some file.

可用性 :Unix,非 Emscripten,非 WASI。

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.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_PROTOCOL

Exit code that means that a protocol exchange was illegal, invalid, or not understood.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_NOPERM

Exit code that means that there were insufficient permissions to perform the operation (but not intended for file system problems).

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_CONFIG

Exit code that means that some kind of configuration error occurred.

可用性 :Unix,非 Emscripten,非 WASI。

os. EX_NOTFOUND

退出代码意味着某些事情像 an entry was not found。

可用性 :Unix,非 Emscripten,非 WASI。

os. fork ( )

分叉子级进程。返回 0 在子级和子级进程 ID 在父级。若发生错误 OSError 被引发。

注意,某些平台 (包括 FreeBSD <= 6.3 和 Cygwin) 有已知问题当使用 fork() 从线程。

引发 审计事件 os.fork 不带自变量。

3.8 版改变: 调用 fork() 在子解释器中不再被支持 ( RuntimeError 被引发)。

警告

ssl 了解应用程序使用 SSL 模块采用 fork()。

可用性 :Unix,非 Emscripten,非 WASI。

os. forkpty ( )

分叉子级进程,使用新的伪终端作为子级进程的控制终端。返回一对 (pid, fd) ,其中 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 模块。若出现错误 OSError 被引发。

引发 审计事件 os.forkpty 不带自变量。

3.8 版改变: 调用 forkpty() 在子解释器中不再被支持 ( RuntimeError 被引发)。

可用性 :Unix,非 Emscripten,非 WASI。

os. kill ( pid , sig , / )

发送信号 sig 给进程 pid 。可用主机平台特定信号常量的定义在 signal 模块。

Windows: signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT 信号是特殊信号,只能发送给共享公共控制台窗口的控制台进程 (如:某些子进程)。任何其它值的 sig 将导致进程被TerminateProcess API 无条件杀除,且退出代码将设为 sig 。Windows 版本的 kill() 此外还需杀除进程句柄。

另请参阅 signal.pthread_kill() .

引发 审计事件 os.kill 采用自变量 pid , sig .

可用性 :Unix、Windows、非 Emscripten、非 WASI。

3.2 版新增: Windows 支持。

os. killpg ( pgid , sig , / )

发送信号 sig 给进程组 pgid .

引发 审计事件 os.killpg 采用自变量 pgid , sig .

可用性 :Unix,非 Emscripten,非 WASI。

os. nice ( increment , / )

添加 increment 到进程的 niceness (好感度)。返回新的好感度。

可用性 :Unix,非 Emscripten,非 WASI。

os. pidfd_open ( pid , flags = 0 )

返回的文件描述符引用进程 pid 。此描述符可以用于履行不带竞争和信号的进程管理。 flags 自变量是为未来扩展而提供的;目前没有定义标志值。

pidfd_open(2) 手册页了解更多细节。

可用性 : Linux >= 5.3

3.9 版新增。

os. plock ( op , / )

Lock program segments into memory. The value of op (defined in <sys/lock.h> ) determines which segments are locked.

可用性 :Unix,非 Emscripten,非 WASI。

os. popen ( cmd , mode = 'r' , buffering = - 1 )

打开管道到或来自命令 cmd 。返回值是连接管道的打开文件对象,可以读取或写入从属 mode is 'r' (默认) 或 'w' buffering 自变量拥有相同含义如相应自变量对于内置 open() 函数。返回的文件对象读取或写入文本字符串而不是字节。

close 方法返回 None 若子进程成功退出,或子进程返回代码若存在错误。在 POSIX 系统,若返回代码为正值,表示进程的返回值左移一字节。若返回代码为负值,将由返回代码否定值所给出的信号终止进程 (例如:返回值可能是 - signal.SIGKILL 若子进程被杀除)。在 Windows 系统,返回值包含来自子级进程的有符号整数返回代码。

在 Unix, waitstatus_to_exitcode() 可以用于转换 close 方法结果 (退出状态) 成退出代码若它不是 None 。在 Windows, close 方法结果直接是退出代码 (或 None ).

这的实现是使用 subprocess.Popen ;见该类的文档编制,了解管理和与子进程通信的更强大办法。

可用性 :非 Emscripten,非 WASI。

注意

Python UTF-8 模式 影响 encoding 用于 cmd 和管道内容。

popen() 是简单包裹器围绕 subprocess.Popen 。使用 subprocess.Popen or subprocess.run() 控制选项 (像:encoding)。

os. posix_spawn ( path , argv , env , * , file_actions = None , setpgroup = None , resetids = False , setsid = False , setsigmask = () , setsigdef = () , scheduler = None )

包裹 posix_spawn() C 库 API 为用于 Python。

大多数用户应该使用 subprocess.run() 而不是 posix_spawn() .

仅位置自变量 path , args ,和 env 类似 execve() .

path parameter is the path to the executable file. The path should contain a directory. Use posix_spawnp() to pass an executable file without directory.

file_actions argument may be a sequence of tuples describing actions to take on specific file descriptors in the child process between the C library implementation’s fork() and exec() steps. The first item in each tuple must be one of the three type indicator listed below describing the remaining tuple elements:

os. POSIX_SPAWN_OPEN

( os.POSIX_SPAWN_OPEN , fd , path , flags , mode )

履行 os.dup2(os.open(path, flags, mode), fd) .

os. POSIX_SPAWN_CLOSE

( os.POSIX_SPAWN_CLOSE , fd )

履行 os.close(fd) .

os. POSIX_SPAWN_DUP2

( os.POSIX_SPAWN_DUP2 , fd , new_fd )

履行 os.dup2(fd, new_fd) .

These tuples correspond to the C library posix_spawn_file_actions_addopen() , posix_spawn_file_actions_addclose() ,和 posix_spawn_file_actions_adddup2() API calls used to prepare for the posix_spawn() call itself.

setpgroup argument will set the process group of the child to the value specified. If the value specified is 0, the child’s process group ID will be made the same as its process ID. If the value of setpgroup is not set, the child will inherit the parent’s process group ID. This argument corresponds to the C library POSIX_SPAWN_SETPGROUP 标志。

resetids 自变量为 True it will reset the effective UID and GID of the child to the real UID and GID of the parent process. If the argument is False , then the child retains the effective UID and GID of the parent. In either case, if the set-user-ID and set-group-ID permission bits are enabled on the executable file, their effect will override the setting of the effective UID and GID. This argument corresponds to the C library POSIX_SPAWN_RESETIDS 标志。

setsid 自变量为 True , it will create a new session ID for posix_spawn . setsid requires POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP flag. Otherwise, NotImplementedError 被引发。

setsigmask argument will set the signal mask to the signal set specified. If the parameter is not used, then the child inherits the parent’s signal mask. This argument corresponds to the C library POSIX_SPAWN_SETSIGMASK 标志。

sigdef argument will reset the disposition of all signals in the set specified. This argument corresponds to the C library POSIX_SPAWN_SETSIGDEF 标志。

scheduler argument must be a tuple containing the (optional) scheduler policy and an instance of sched_param with the scheduler parameters. A value of None in the place of the scheduler policy indicates that is not being provided. This argument is a combination of the C library POSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDULER 标志。

引发 审计事件 os.posix_spawn 采用自变量 path , argv , env .

3.8 版新增。

可用性 :Unix,非 Emscripten,非 WASI。

os. posix_spawnp ( path , argv , env , * , file_actions = None , setpgroup = None , resetids = False , setsid = False , setsigmask = () , setsigdef = () , scheduler = None )

包裹 posix_spawnp() C 库 API 为用于 Python。

类似于 posix_spawn() except that the system searches for the executable file in the list of directories specified by the PATH environment variable (in the same way as for execvp(3) ).

引发 审计事件 os.posix_spawn 采用自变量 path , argv , env .

3.8 版新增。

可用性 : POSIX, not Emscripten, not WASI.

posix_spawn() 文档编制。

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() 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 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.

注意, fork() calls made by third-party C code may not call those functions, unless it explicitly calls PyOS_BeforeFork() , PyOS_AfterFork_Parent() and PyOS_AfterFork_Child() .

没有办法取消函数注册。

可用性 :Unix,非 Emscripten,非 WASI。

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 )

执行程序 path 在新的进程中。

(注意, subprocess 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 替换较旧函数采用 subprocess 模块 章节。)

mode is P_NOWAIT , this function returns the process id of the new process; if mode is P_WAIT , returns the process’s exit code if it exits normally, or -signal ,其中 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() 函数。

Note on VxWorks, this function doesn’t return -signal when the new process is killed. Instead it raises OSError exception.

The “l” and “v” variants of the spawn* 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() , spawnlpe() , spawnvp() ,和 spawnvpe() ) 将使用 PATH environment variable to locate the program file . When the environment is being replaced (using one of the spawn*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, spawnl() , spawnle() , spawnv() ,和 spawnve() , will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path.

For spawnle() , spawnlpe() , spawnve() ,和 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() , spawnlp() , spawnv() ,和 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 .

作为范例,以下调用 spawnlp() and spawnvpe() 是等效的:

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)
						

引发 审计事件 os.spawn 采用自变量 mode , path , args , env .

可用性 :Unix、Windows、非 Emscripten、非 WASI。

spawnlp() , spawnlpe() , spawnvp() and spawnvpe() 不可用于 Windows。 spawnle() and spawnve() 在 Windows 不是线程安全的;建议使用 subprocess 模块代替。

3.6 版改变: 接受 像路径对象 .

os. P_NOWAIT
os. P_NOWAITO

可能的值对于 mode 参数用于 spawn* 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.

可用性 :Unix、Windows。

os. P_WAIT

可能的值对于 mode 参数用于 spawn* family of functions. If this is given as mode 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 若信号杀除进程。

可用性 :Unix、Windows。

os. P_DETACH
os. P_OVERLAY

可能的值对于 mode 参数用于 spawn* family of functions. These are less portable than those listed above. P_DETACH 类似于 P_NOWAIT , but the new process is detached from the console of the calling process. If P_OVERLAY is used, the current process will be replaced; the spawn* 函数不会返回。

可用性 :Windows。

os. startfile ( path [ , operation ] [ , arguments ] [ , cwd ] [ , show_cmd ] )

采用关联应用程序启动文件。

operation 未指定或 'open' ,这的举动像在 Windows 资源管理器中双击文件,或将文件名作为自变量赋予 start 命令从交互命令 Shell:采用其扩展名关联的任何应用程序 (若有的话) 打开文件。

当另一 operation 有给定,它必须是指定应该对文件做什么的命令动词。由 Microsoft 文档化的常见动词包括 'print' and 'edit' (用于文件) 及 'explore' and 'find' (用于目录)。

当发起应用程序时,指定 arguments 以单字符串形式传递。此自变量可能不起作用,当使用此函数发起文档时。

默认工作目录是继承的,但可以覆盖通过 cwd 自变量。这应该是绝对路径。相对 path 将针对此自变量进行解析。

使用 show_cmd 可以覆盖默认窗口样式。这是否有任何作用从属正发起的应用程序。值为整数支持 Win32 ShellExecute() 函数。

startfile() 尽快返回,一旦发起关联应用程序。没有等待应用程序关闭的选项,也没有检索应用程序退出状态的办法。 path 参数相对于当前目录或为 cwd 。若想要使用绝对路径,确保第一个字符不是斜杠 ( '/' ) 使用 pathlib os.path.normpath() 函数以确保 Win32 正确编码路径。

要缩减解释器启动开销,Win32 ShellExecute() 函数不被解析直到首次调用此函数为止。若函数无法解析, NotImplementedError 会被引发。

引发 审计事件 os.startfile 采用自变量 path , operation .

引发 审计事件 os.startfile/2 采用自变量 path , operation , arguments , cwd , show_cmd .

可用性 :Windows。

3.10 版改变: 添加 arguments , cwd and show_cmd 自变量,和 os.startfile/2 审计事件。

os. system ( 命令 )

在子 Shell 执行命令 (字符串)。这的实现是通过调用标准 C 函数 system() ,且拥有相同局限性。更改 sys.stdin 等未反映在执行命令环境中。若 命令 生成任何输出,会被发送给解释器标准输出流。C 标准未指定 C 函数返回值的含义,所以 Python 函数的返回值从属系统。

在 Unix,返回值是进程的退出状态,指定编码格式为 wait() .

在 Windows,返回值是由系统 Shell 所返回的值后于运行 命令 。Shell 的给定是通过 Windows 环境变量 COMSPEC :通常是 cmd.exe ,返回运行命令的退出状态;当系统使用非本机 Shell 时,请翻阅 Shell 文档编制。

subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the 替换较旧函数采用 subprocess 模块 section in the subprocess documentation for some helpful recipes.

在 Unix, waitstatus_to_exitcode() can be used to convert the result (exit status) into an exit code. On Windows, the result is directly the exit code.

引发 审计事件 os.system 采用自变量 command .

可用性 :Unix、Windows、非 Emscripten、非 WASI。

os. times ( )

返回当前全局处理时间。返回值是具有 5 属性的对象:

  • user - 用户时间

  • system - 系统时间

  • children_user - 所有子级进程的用户时间

  • children_system - 所有子级进程的系统时间

  • elapsed - 从过去固定点起的真实消耗时间

为向后兼容,此对象的行为还像 5 元组包含 user , system , children_user , children_system ,和 elapsed in that order.

见 Unix 手册页 times(2) and times(3) 手册页在 Unix 或 the GetProcessTimes MSDN on Windows. On Windows, only user and system are known; the other attributes are zero.

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

waitstatus_to_exitcode() 可以用于将退出状态转换成退出代码。

可用性 :Unix,非 Emscripten,非 WASI。

另请参阅

waitpid() can be used to wait for the completion of a specific child process and has more options.

os. waitid ( idtype , id , 选项 , / )

Wait for the completion of one or more child processes. idtype 可以是 P_PID , P_PGID , P_ALL ,或 P_PIDFD on Linux. id specifies the pid to wait on. 选项 is constructed from the ORing of one or more of WEXITED , WSTOPPED or WCONTINUED and additionally may be ORed with WNOHANG or 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 is specified and there are no children in a waitable state.

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增。

os. P_PID
os. P_PGID
os. P_ALL

这些是可能的值对于 idtype in waitid() . They affect how id is interpreted.

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增。

os. P_PIDFD

This is a Linux-specific idtype that indicates that id is a file descriptor that refers to a process.

可用性 : Linux >= 5.4

3.9 版新增。

os. WEXITED
os. WSTOPPED
os. WNOWAIT

Flags that can be used in 选项 in waitid() that specify what child signal to wait for.

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增。

os. CLD_EXITED
os. CLD_KILLED
os. CLD_DUMPED
os. CLD_TRAPPED
os. CLD_STOPPED
os. CLD_CONTINUED

这些是可能的值对于 si_code in the result returned by waitid() .

可用性 :Unix,非 Emscripten,非 WASI。

3.3 版新增。

3.9 版改变: 添加 CLD_KILLED and CLD_STOPPED 值。

os. waitpid ( pid , 选项 , / )

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() ). The semantics of the call are affected by the value of the integer 选项 , which should be 0 for normal operation.

pid 大于 0 , 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 小于 -1 , status is requested for any process in the process group -pid (the absolute value of pid ).

An 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 选项 不起作用。 pid can refer to any process whose id is known, not necessarily a child process. The spawn* functions called with P_NOWAIT return suitable process handles.

waitstatus_to_exitcode() 可以用于将退出状态转换成退出代码。

可用性 :Unix,非 Emscripten,非 WASI。

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,函数现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

os. wait3 ( 选项 )

类似于 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 . getrusage() for details on resource usage information. The option argument is the same as that provided to waitpid() and wait4() .

waitstatus_to_exitcode() can be used to convert the exit status into an exitcode.

可用性 :Unix,非 Emscripten,非 WASI。

os. wait4 ( pid , 选项 )

类似于 waitpid() , except a 3-element tuple, containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource . getrusage() for details on resource usage information. The arguments to wait4() are the same as those provided to waitpid() .

waitstatus_to_exitcode() can be used to convert the exit status into an exitcode.

可用性 :Unix,非 Emscripten,非 WASI。

os. waitstatus_to_exitcode ( status )

Convert a wait status to an exit code.

在 Unix:

  • If the process exited normally (if WIFEXITED(status) is true), return the process exit status (return WEXITSTATUS(status) ): result greater than or equal to 0.

  • If the process was terminated by a signal (if WIFSIGNALED(status) is true), return -signum where signum is the number of the signal that caused the process to terminate (return -WTERMSIG(status) ): result less than 0.

  • 否则,引发 ValueError .

在 Windows,返回 status shifted right by 8 bits.

On Unix, if the process is being traced or if waitpid() was called with WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true. This function must not be called if WIFSTOPPED(status) 为 True。

另请参阅

WIFEXITED() , WEXITSTATUS() , WIFSIGNALED() , WTERMSIG() , WIFSTOPPED() , WSTOPSIG() 函数。

可用性 :Unix、Windows、非 Emscripten、非 WASI。

3.9 版新增。

os. WNOHANG

The option for waitpid() to return immediately if no child process status is available immediately. The function returns (0, 0) 在此情况下。

可用性 :Unix,非 Emscripten,非 WASI。

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.

可用性 :Unix,非 Emscripten,非 WASI。

Some Unix systems.

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.

可用性 :Unix,非 Emscripten,非 WASI。

The following functions take a process status code as returned by system() , wait() ,或 waitpid() as a parameter. They may be used to determine the disposition of a process.

os. WCOREDUMP ( status , / )

返回 True if a core dump was generated for the process, otherwise return False .

才应雇用此函数若 WIFSIGNALED() 为 True。

可用性 :Unix,非 Emscripten,非 WASI。

os. WIFCONTINUED ( status )

返回 True if a stopped child has been resumed by delivery of SIGCONT (if the process has been continued from a job control stop), otherwise return False .

WCONTINUED 选项。

可用性 :Unix,非 Emscripten,非 WASI。

os. WIFSTOPPED ( status )

返回 True if the process was stopped by delivery of a signal, otherwise return False .

WIFSTOPPED() only returns True waitpid() call was done using WUNTRACED option or when the process is being traced (see ptrace(2) ).

可用性 :Unix,非 Emscripten,非 WASI。

os. WIFSIGNALED ( status )

返回 True 若进程被信号终止,否则返回 False .

可用性 :Unix,非 Emscripten,非 WASI。

os. WIFEXITED ( status )

返回 True if the process exited terminated normally, that is, by calling exit() or _exit() ,或通过返回自 main() ;否则返回 False .

可用性 :Unix,非 Emscripten,非 WASI。

os. WEXITSTATUS ( status )

返回进程退出状态。

才应雇用此函数若 WIFEXITED() 为 True。

可用性 :Unix,非 Emscripten,非 WASI。

os. WSTOPSIG ( status )

Return the signal which caused the process to stop.

才应雇用此函数若 WIFSTOPPED() 为 True。

可用性 :Unix,非 Emscripten,非 WASI。

os. WTERMSIG ( status )

Return the number of the signal that caused the process to terminate.

才应雇用此函数若 WIFSIGNALED() 为 True。

可用性 :Unix,非 Emscripten,非 WASI。

接口到调度器

这些函数控制操作系统,如何分配进程 CPU 时间。它们只可用于某些 Unix 平台。更多详细信息,请翻阅 Unix 手册页。

3.3 版新增。

下列调度策略被暴露,若操作系统支持它们。

os. SCHED_OTHER

默认调度策略。

os. SCHED_BATCH

Scheduling policy for CPU-intensive processes that tries to preserve interactivity on the rest of the computer.

os. SCHED_IDLE

极低优先级后台任务的调度策略。

os. SCHED_SPORADIC

零星服务器程序的调度策略。

os. SCHED_FIFO

FIFO (先进先出) 调度策略。

os. SCHED_RR

循环调度策略。

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() , sched_setscheduler() ,和 sched_getparam() . It is immutable.

此刻,只有一个可能参数:

sched_priority

调度策略的调度优先级。

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 pid of 0 means the calling process. policy is one of the scheduling policy constants above. param sched_param 实例。

os. sched_getscheduler ( pid , / )

Return the scheduling policy for the process with PID pid pid of 0 means the calling process. The result is one of the scheduling policy constants above.

os. sched_setparam ( pid , param , / )

Set the scheduling parameters for the process with PID pid pid of 0 means the calling process. param sched_param 实例。

os. sched_getparam ( pid , / )

Return the scheduling parameters as a sched_param instance for the process with PID pid 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 pid of 0 means the calling process.

os. sched_yield ( )

自愿放弃 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 , / )

返回 CPU 集的进程具有 PID pid (或当前进程若为 0) 限定。

杂项系统信息

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.

若配置值的指定通过 name 未定义, None 被返回。

name 是字符串且未知, ValueError 被引发。若特定值对于 name 主机系统不支持,即使包括在 confstr_names OSError 被引发采用 errno.EINVAL 对于错误编号。

可用性 :Unix。

os. confstr_names

字典映射的名称接受通过 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.

可用性 :Unix。

os. cpu_count ( )

返回系统中的 CPU 数。返回 None 若不确定。

此数字不等效于当前进程可以使用的 CPU 数。可用 CPU 数可以获得采用 len(os.sched_getaffinity(0))

3.4 版新增。

os. getloadavg ( )

返回最后 1 分钟、5 分钟及 15 分钟内系统运行队列中的平均进程数或引发 OSError 若难以获得平均负载。

可用性 :Unix。

os. sysconf ( name , / )

Return integer-valued system configuration values. If the configuration value specified by name 未定义, -1 is returned. The comments regarding the name parameter for confstr() apply here as well; the dictionary that provides information on the known names is given by sysconf_names .

可用性 :Unix。

os. sysconf_names

字典映射的名称接受通过 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.

可用性 :Unix。

3.11 版改变: 添加 'SC_MINSIGSTKSZ' 名称。

下列数据值用于支持路径操纵操作。所有平台都有定义这些。

路径名的高级操作的定义在 os.path 模块。

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. 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. 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() and os.path.join() — but it is occasionally useful. Also available via os.path .

os. altsep

操作系统用来分隔路径名分量的替代字符,或 None 若只存在一个分隔符。这被设为 '/' 在 Windows 系统 sep 是 反斜杠。也可用凭借 os.path .

os. extsep

The character which separates the base filename from the extension; for example, the '.' in os.py . Also available via os.path .

os. pathsep

The character conventionally used by the operating system to separate search path components (as in PATH ),譬如 ':' for POSIX or ';' 为 Windows。也可用凭借 os.path .

os. defpath

The default search path used by exec*p* and spawn*p* if the environment doesn’t have a 'PATH' key. Also available via os.path .

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' 代替,在所有平台。

os. devnull

null 设备的文件路径。例如: '/dev/null' 为 POSIX, 'nul' 为 Windows。也可用凭借 os.path .

os. RTLD_LAZY
os. RTLD_NOW
os. RTLD_GLOBAL
os. RTLD_LOCAL
os. RTLD_NODELETE
os. RTLD_NOLOAD
os. RTLD_DEEPBIND

标志用于 setdlopenflags() and getdlopenflags() 函数。见 Unix 手册页 dlopen(3) 了解不同标志的具体含义。

3.3 版新增。

随机数

os. getrandom ( size , flags = 0 )

获取直到 size 随机字节。函数返回字节数可以小于请求字节数。

这些 bytes 可以用于种子用户空间随机数生成器 (或用于加密目的)。

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 设备。

The flags argument is a bit mask that can contain zero or more of the following values ORed together: os.GRND_RANDOM and GRND_NONBLOCK .

另请参阅 Linux getrandom() 手册页 .

可用性 : Linux >= 3.17.

3.6 版新增。

os. urandom ( size , / )

Return a bytestring 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.

在 Linux,若 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 for the rationale. On Linux, the getrandom() function can be used to get random bytes in non-blocking mode (using the GRND_NONBLOCK flag) or to poll until the system urandom entropy pool is initialized.

在像 Unix 系统,随机字节读取自 /dev/urandom 设备。若 /dev/urandom device is not available or not readable, the NotImplementedError 异常被引发。

在 Windows,它将使用 BCryptGenRandom() .

另请参阅

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 .

3.6.0 版改变: 在 Linux, getrandom() is now used in blocking mode to increase the security.

3.5.2 版改变: 在 Linux,若 getrandom() syscall blocks (the urandom entropy pool is not initialized yet), fall back on reading /dev/urandom .

3.5 版改变: 在 Linux 3.17 及更高版本, 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.

3.11 版改变: 在 Windows, BCryptGenRandom() 被使用而不是 CryptGenRandom() which is deprecated.

os. GRND_NONBLOCK

默认情况下,当读取自 /dev/random , 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.

GRND_NONBLOCK 标志有设置,那么 getrandom() does not block in these cases, but instead immediately raises BlockingIOError .

3.6 版新增。

os. GRND_RANDOM

若此位有设置,那么随机字节抽取自 /dev/random 池而不是 /dev/urandom 池。

3.6 版新增。

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1