内容表

  • os — 杂项操作系统接口
    • 文件名、命令行自变量和环境变量
    • Python UTF-8 模式
    • 进程参数
    • 文件对象创建
    • 文件描述符操作
      • 查询终端的尺寸
      • 文件描述符的继承
    • 文件和目录
      • Linux 扩展属性
    • 进程管理
    • 接口到调度器
    • 杂项系统信息
    • 随机数

上一话题

一般操作系统服务

下一话题
就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 一般操作系统服务
  9. os — 杂项操作系统接口

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() 给出系统从属版本信息。

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

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

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

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

3.1 版改变: 在某些系统,使用文件系统编码转换可能失败。在这种情况下,Python 使用 surrogateescape (替代转义) 编码错误处理程序 , which means that undecodable bytes are replaced by a Unicode character U+DC xx on decoding, and these are again translated to the original byte on encoding.

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

另请参阅 区域设置编码 .

Python UTF-8 模式 ¶

Added in version 3.7: 见 PEP 540 了解更多细节。

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

  • 使用 UTF-8 作为 文件系统编码 .

  • sys.getfilesystemencoding() 返回 'utf-8' .

  • locale.getpreferredencoding() 返回 'utf-8' ( do_setlocale 自变量不起作用)。

  • sys.stdin , sys.stdout ,和 sys.stderr 都使用 UTF-8 作为它们的文本编码,采用 surrogateescape 错误处理程序 被启用对于 sys.stdin and sys.stdout ( sys.stderr 继续使用 backslashreplace 如它在默认区域设置感知模式下所做的)

  • 在 Unix, os.device_encoding() 返回 'utf-8' 而不是设备编码。

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

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

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

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

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

The 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 若愿意使用不同的编码。

On Windows, the keys are converted to uppercase. This also applies when getting, setting, or deleting an item. For example, environ['monty'] = 'python' maps the key 'MONTY' to the value 'python' .

注意

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

注意

在某些平台,包括 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 .

Added in version 3.2.

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

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

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

os. fsencode ( filename ) ¶

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

fsdecode() 是反函数。

Added in version 3.2.

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

os. fsdecode ( filename ) ¶

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

fsencode() 是反函数。

Added in version 3.2.

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

os. fspath ( path ) ¶

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

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

Added in version 3.6.

class os. PathLike ¶

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

Added in version 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。

Added in version 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 被使用。

Added in version 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。

Added in version 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。

Added in version 3.3.

os. PRIO_PROCESS ¶
os. PRIO_PGRP ¶
os. PRIO_USER ¶

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

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

Added in version 3.3.

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

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

可用性 : macOS

3.12 版添加。

os. getresuid ( ) ¶

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

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

Added in version 3.2.

os. getresgid ( ) ¶

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

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

Added in version 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。

Added in version 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. setns ( fd , nstype = 0 ) ¶

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

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

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

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

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

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

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

3.12 版添加。

另请参阅

The unshare() 函数。

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。

Added in version 3.3.

os. setregid ( rgid , egid , / ) ¶

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

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

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

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

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

Added in version 3.2.

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

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

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

Added in version 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)。

Added in version 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 也可用。

os. unshare ( flags ) ¶

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

可用性 : Linux >= 2.6.16.

3.12 版添加。

另请参阅

The setns() 函数。

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

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

文件对象创建 ¶

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

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

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

文件描述符操作 ¶

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

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

The 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 ,那么 src is read from the current position; respectively for offset_dst .

In Linux kernel older than 5.3, the files pointed to by src and dst must reside in the same filesystem, otherwise an OSError 被引发采用 errno 设为 errno.EXDEV .

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

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

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

注意

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

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

Added in version 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) 时, 新文件描述符 可继承 .

可用性 :非 WASI。

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

os. dup2 ( fd , fd2 , 可继承 = True ) ¶

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

可用性 :非 WASI。

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

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

另请参阅

The 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、Windows。

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

On Windows, this function is limited to pipes.

Added in version 3.5.

Changed in version 3.12: Added support for pipes on Windows.

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。

Added in version 3.3.

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

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

可用性 :Unix。

Added in version 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。

Added in version 3.11.

os. lseek ( fd , pos , whence , / ) ¶

Set the current position of file descriptor fd to position pos , modified by whence , and return the new position in bytes relative to the start of the file. Valid values for whence 是:

  • SEEK_SET or 0 – set pos relative to the beginning of the file

  • SEEK_CUR or 1 – set pos relative to the current file position

  • SEEK_END or 2 – set pos relative to the end of the file

  • SEEK_HOLE – set pos to the next data location, relative to pos

  • SEEK_DATA – set pos to the next data hole, relative to pos

3.3 版改变: Add support for SEEK_HOLE and SEEK_DATA .

os. SEEK_SET ¶
os. SEEK_CUR ¶
os. SEEK_END ¶

参数用于 lseek() 函数和 seek() method on 像文件对象 , for whence to adjust the file position indicator.

SEEK_SET

Adjust the file position relative to the beginning of the file.

SEEK_CUR

Adjust the file position relative to the current file position.

SEEK_END

Adjust the file position relative to the end of the file.

Their values are 0, 1, and 2, respectively.

os. SEEK_HOLE ¶
os. SEEK_DATA ¶

参数用于 lseek() 函数和 seek() method on 像文件对象 , for seeking file data and holes on sparsely allocated files.

SEEK_DATA

Adjust the file offset to the next location containing data, relative to the seek position.

SEEK_HOLE

Adjust the file offset to the next location containing a hole, relative to the seek position. A hole is defined as a sequence of zeros.

注意

These operations only make sense for filesystems that support them.

可用性 : Linux >= 3.1, macOS, Unix

Added in version 3.3.

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_SYMLINK ¶
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。

Added in version 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。

Added in version 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。

Added in version 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。

Added in version 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。

Added in version 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:

  • RWF_HIPRI

  • RWF_NOWAIT

Return the total number of bytes actually read which can be less than the total capacity of all the objects.

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

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.

Added in version 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.

Added in version 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.

Added in version 3.7.

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

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

返回实际写入的字节数。

可用性 :Unix。

Added in version 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:

  • RWF_DSYNC

  • RWF_SYNC

  • RWF_APPEND

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.

Added in version 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.

Added in version 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.

Added in version 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.

Added in version 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() .

Added in version 3.3.

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

os. SF_NODISKIO ¶
os. SF_MNOWAIT ¶
os. SF_SYNC ¶

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

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

Added in version 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。

Added in version 3.11.

os. set_blocking ( fd , blocking , / ) ¶

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

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

可用性 :Unix、Windows。

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

On Windows, this function is limited to pipes.

Added in version 3.5.

Changed in version 3.12: Added support for pipes on Windows.

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 ,那么 src is read from the current position; respectively for offset_dst . The offset associated to the file descriptor that refers to a pipe must be None . The files pointed to by src and dst must reside in the same filesystem, otherwise an OSError 被引发采用 errno 设为 errno.EXDEV .

This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel. Additionally, some filesystems could implement extra optimizations. The copy is done as if both files are opened as binary.

Upon successful completion, returns the number of bytes spliced to or from the pipe. A return value of 0 means end of input. If src refers to a pipe, then this means that there was no data to transfer, and it would not make sense to block because there are no writers connected to the write end of the pipe.

可用性 : Linux >= 2.6.17 with glibc >= 2.5

Added in version 3.10.

os. SPLICE_F_MOVE ¶
os. SPLICE_F_NONBLOCK ¶
os. SPLICE_F_MORE ¶

Added in version 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。

Added in version 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。

Added in version 3.3.

查询终端的尺寸 ¶

Added in version 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 ¶

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

文件描述符的继承 ¶

Added in version 3.4.

A file descriptor has an “inheritable” flag which indicates if the file descriptor can be inherited by child processes. Since Python 3.4, file descriptors created by Python are non-inheritable by default.

On UNIX, non-inheritable file descriptors are closed in child processes at the execution of a new program, other file descriptors are inherited.

On Windows, non-inheritable handles and file descriptors are closed in child processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout and stderr), which are always inherited. Using spawn* functions, all inheritable handles and all inheritable file descriptors are inherited. Using the subprocess module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the close_fds 参数为 False .

在 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 , 可继承 , / ) ¶

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 , 可继承 , / ) ¶

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 .

  • 不遵循符号链接: 若 follow_symlinks is False , and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself rather than the file pointed to by the link. (For POSIX systems, Python will call the l... variant of the function.)

    You can check whether or not follow_symlinks is supported for a particular function on your platform using os.supports_follow_symlinks . If it’s unavailable, using it will raise a NotImplementedError .

os. 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 模块):

  • stat.UF_NODUMP

  • stat.UF_IMMUTABLE

  • stat.UF_APPEND

  • stat.UF_OPAQUE

  • stat.UF_NOUNLINK

  • stat.UF_COMPRESSED

  • stat.UF_HIDDEN

  • stat.SF_ARCHIVED

  • stat.SF_IMMUTABLE

  • stat.SF_APPEND

  • stat.SF_NOUNLINK

  • stat.SF_SNAPSHOT

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

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

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

  • stat.S_ISUID

  • stat.S_ISGID

  • stat.S_ENFMT

  • stat.S_ISVTX

  • stat.S_IREAD

  • stat.S_IWRITE

  • stat.S_IEXEC

  • stat.S_IRWXU

  • stat.S_IRUSR

  • stat.S_IWUSR

  • stat.S_IXUSR

  • stat.S_IRWXG

  • stat.S_IRGRP

  • stat.S_IWGRP

  • stat.S_IXGRP

  • stat.S_IRWXO

  • stat.S_IROTH

  • stat.S_IWOTH

  • stat.S_IXOTH

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

注意

尽管 Windows 支持 chmod() , you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

函数在 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) .

lchmod() is not part of POSIX, but Unix implementations may have it if changing the mode of symbolic links is supported.

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

可用性 : Unix, not Linux, FreeBSD >= 1.3, NetBSD >= 1.3, not OpenBSD

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 版改变: 接受 像路径对象 .

os. link ( src , dst , * , src_dir_fd = None , dst_dir_fd = None , follow_symlinks = True ) ¶

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

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

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

可用性 : Unix, Windows, not Emscripten.

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

另请参阅

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

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

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

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

os. listdrives ( ) ¶

Return a list containing the names of drives on a Windows system.

A drive name typically looks like 'C:\\' . Not every drive name will be associated with a volume, and some may be inaccessible for a variety of reasons, including permissions, network connectivity or missing media. This function does not test for access.

可能引发 OSError if an error occurs collecting the drive names.

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

可用性 : Windows

3.12 版添加。

os. listmounts ( volume ) ¶

Return a list containing the mount points for a volume on a Windows system.

volume must be represented as a GUID path, like those returned by os.listvolumes() . Volumes may be mounted in multiple locations or not at all. In the latter case, the list will be empty. Mount points that are not associated with a volume will not be returned by this function.

The mount points return by this function will be absolute paths, and may be longer than the drive name.

引发 OSError if the volume is not recognized or if an error occurs collecting the paths.

引发 审计事件 os.listmounts 采用自变量 volume .

可用性 : Windows

3.12 版添加。

os. listvolumes ( ) ¶

Return a list containing the volumes in the system.

Volumes are typically represented as a GUID path that looks like \\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\ . Files can usually be accessed through a GUID path, permissions allowing. However, users are generally not familiar with them, and so the recommended use of this function is to retrieve mount points using os.listmounts() .

可能引发 OSError if an error occurs collecting the volumes.

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

可用性 : Windows

3.12 版添加。

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

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

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

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

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

另请参阅

The 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() 以明确设置它们。

On Windows, a mode of 0o700 is specifically handled to apply access control to the new directory such that only the current user and administrators have access. Other values of mode 被忽略。

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

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

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

3.3 版改变: 添加 dir_fd 参数。

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

Changed in version 3.12.4: Windows now handles a mode of 0o700 .

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

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

The 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 版改变: The 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. readlink ( path , * , dir_fd = None ) ¶

返回符号链接指向路径的表示字符串。结果可能是绝对 (或相对) 路径名;若是相对的,可以将它转换成绝对路径名使用 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。

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 是目录, OSError 被引发。使用 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 is always raised. The operation may fail if src and dst are on different filesystems. Use shutil.move() to support moves to a different filesystem.

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

Added in version 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 .

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

scandir. close ( ) ¶

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

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

Added in version 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 函数。

Added in version 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 自变量。

The 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 属性。

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

is_symlink ( ) ¶

返回 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 会被捕获但不引发。

is_junction ( ) ¶

返回 True if this entry is a junction (even if broken); return False if the entry points to a regular directory, any kind of file, a symlink, or if it doesn’t exist anymore.

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

3.12 版添加。

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() , is_junction() ,和 stat() 方法。

Added in version 3.5.

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

Changed in version 3.12: The st_ctime attribute of a stat result is deprecated on Windows. The file creation time is properly available as st_birthtime , and in the future st_ctime may be changed to return zero or the metadata change time, if available.

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 parameters, specifying a file descriptor instead of a path.

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 。通常:

  • Unix 中的 Inode 编号,

  • the 文件索引 在 Windows

st_dev ¶

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

st_nlink ¶

硬链接数。

st_uid ¶

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

st_gid ¶

文件所有者的组标识符。

st_size ¶

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

时间戳:

st_atime ¶

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

st_mtime ¶

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

st_ctime ¶

Time of most recent metadata change expressed in seconds.

Changed in version 3.12: st_ctime is deprecated on Windows. Use st_birthtime for the file creation time. In the future, st_ctime will contain the time of the most recent metadata change, as for other platforms.

st_atime_ns ¶

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

Added in version 3.3.

st_mtime_ns ¶

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

Added in version 3.3.

st_ctime_ns ¶

Time of most recent metadata change expressed in nanoseconds as an integer.

Added in version 3.3.

Changed in version 3.12: st_ctime_ns is deprecated on Windows. Use st_birthtime_ns for the file creation time. In the future, st_ctime will contain the time of the most recent metadata change, as for other platforms.

st_birthtime ¶

Time of file creation expressed in seconds. This attribute is not always available, and may raise AttributeError .

Changed in version 3.12: st_birthtime is now available on Windows.

st_birthtime_ns ¶

Time of file creation expressed in nanoseconds as an integer. This attribute is not always available, and may raise AttributeError .

3.12 版添加。

注意

准确含义和分辨率对于 st_atime , st_mtime , st_ctime and st_birthtime attributes depend on the operating system and the file system. For example, on Windows systems using the FAT32 file systems, st_mtime 拥有 2 秒分辨率,和 st_atime 只有 1 天的分辨率。见操作系统文档编制了解细节。

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

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

st_blocks ¶

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

st_blksize ¶

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

st_rdev ¶

设备类型若是 Inode 设备。

st_flags ¶

用户为文件定义的标志。

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

st_gen ¶

文件生成编号。

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

st_fstype ¶

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

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

st_rsize ¶

文件的实际大小。

st_creator ¶

文件的创建者。

st_type ¶

文件类型。

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

st_file_attributes ¶

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

Added in version 3.5.

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.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 酌情。

Changed in version 3.12: 在 Windows, st_ctime is deprecated. Eventually, it will contain the last metadata change time, for consistency with other platforms, but for now still contains creation time. Use st_birthtime for the creation time.

在 Windows, st_ino may now be up to 128 bits, depending on the file system. Previously it would not be above 64 bits, and larger file identifiers would be arbitrarily packed.

在 Windows, st_rdev no longer returns a value. Previously it would contain the same as st_dev , which was incorrect.

添加 st_birthtime 成员在 Windows。

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 版改变: The ST_RDONLY and ST_NOSUID 常量被添加。

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

3.4 版改变: The 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.

Added in version 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.

Added in version 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
																																																																																																										

Added in version 3.3.

os. supports_follow_symlinks ¶

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
																																																																																																										

Added in version 3.3.

os. symlink ( src , dst , target_is_directory = False , * , dir_fd = None ) ¶

创建的符号链接指向 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 parameter, 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。

Added in version 3.3.

os. truncate ( path , length ) ¶

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

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

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

可用性 :Unix、Windows。

Added in version 3.3.

3.5 版改变: 添加支持 Windows

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

os. unlink ( path , * , dir_fd = None ) ¶

移除 (删除) 文件 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 (including symlinks to directories, and 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。

Added in version 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.

Added in version 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

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

Added in version 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

Added in version 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

Added in version 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

Added in version 3.10.

os. EFD_CLOEXEC ¶

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

可用性 : Linux >= 2.6.27

Added in version 3.10.

os. EFD_NONBLOCK ¶

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

可用性 : Linux >= 2.6.27

Added in version 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

Added in version 3.10.

Linux 扩展属性 ¶

Added in version 3.3.

这些函数只可用于 Linux。

os. getxattr ( path , attribute , * , 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 , attribute , * , 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 , attribute , 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。

Added in version 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. Relative paths must include at least one slash, even on Windows, as plain names will not be resolved.

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 不带自变量。

警告

If you use TLS sockets in an application calling fork() , see the warning in the ssl 文档编制。

警告

On macOS the use of this function is unsafe when mixed with using higher-level system APIs, and that includes using urllib.request .

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

Changed in version 3.12: If Python is able to detect that your process has multiple threads, os.fork() now raises a DeprecationWarning .

We chose to surface this as a warning, when detectable, to better inform developers of a design problem that the POSIX platform specifically notes as not supported. Even in code that appears to work, it has never been safe to mix threading with os.fork() on POSIX platforms. The CPython runtime itself has always made API calls that are not safe for use in the child process when threads existed in the parent (such as malloc and free ).

Users of macOS or users of libc or malloc implementations other than those typically found in glibc to date are among those already more likely to experience deadlocks running such code.

见 this discussion on fork being incompatible with threads for technical details of why we’re surfacing this longstanding platform compatibility problem to developers.

可用性 : POSIX, not Emscripten, not 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 不带自变量。

警告

On macOS the use of this function is unsafe when mixed with using higher-level system APIs, and that includes using urllib.request .

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

Changed in version 3.12: If Python is able to detect that your process has multiple threads, this now raises a DeprecationWarning . See the longer explanation on os.fork() .

可用性 :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 with flags set. This descriptor can be used to perform process management without races and signals.

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

可用性 : Linux >= 5.3

Added in version 3.9.

os. PIDFD_NONBLOCK ¶

This flag indicates that the file descriptor will be non-blocking. If the process referred to by the file descriptor has not yet terminated, then an attempt to wait on the file descriptor using waitid(2) will immediately return the error EAGAIN rather than blocking.

可用性 : Linux >= 5.10

3.12 版添加。

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() 函数。返回的文件对象读取或写入文本字符串而不是字节。

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

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

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

可用性 :非 Emscripten,非 WASI。

注意

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

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

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

The 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 被引发。

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

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

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

Added in version 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 .

Added in version 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。

Added in version 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 is not specified, this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start 命令从交互命令 Shell:采用其扩展名关联的任何应用程序 (若有的话) 打开文件。

当另一 operation 有给定,它必须是指定应该对文件做什么的命令动词。由 Microsoft 文档化的常见动词包括 'open' , '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 文档编制。

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

If there are no children that could be waited for, ChildProcessError 被引发。

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

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

另请参阅

The other wait*() functions documented below can be used to wait for the completion of a specific child process and have more options. waitpid() is the only one also available on Windows.

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

Wait for the completion of a child process.

idtype 可以是 P_PID , P_PGID , P_ALL , or (on Linux) P_PIDFD 。解释 id depends on it; see their individual descriptions.

选项 is an OR combination of flags. At least one of WEXITED , WSTOPPED or WCONTINUED is required; WNOHANG and WNOWAIT are additional optional flags.

The return value is an object representing the data contained in the siginfo_t structure with the following attributes:

  • si_pid (process ID)

  • si_uid (real user ID of the child)

  • si_signo (always SIGCHLD )

  • si_status (the exit status or signal number, depending on si_code )

  • si_code (见 CLD_EXITED for possible values)

若 WNOHANG is specified and there are no matching children in the requested state, None is returned. Otherwise, if there are no matching children that could be waited for, ChildProcessError 被引发。

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

注意

This function is not available on macOS.

Added in version 3.3.

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

选项 is an OR combination of flags. If it contains WNOHANG and there are no matching children in the requested state, (0, 0) is returned. Otherwise, if there are no matching children that could be waited for, ChildProcessError is raised. Other options that can be used are WUNTRACED and WCONTINUED .

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、Windows、非 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 选项 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. P_PID ¶
os. P_PGID ¶
os. P_ALL ¶
os. P_PIDFD ¶

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

  • P_PID - wait for the child whose PID is id .

  • P_PGID - wait for any child whose progress group ID is id .

  • P_ALL - wait for any child; id 被忽略。

  • P_PIDFD - wait for the child identified by the file descriptor id (a process file descriptor created with pidfd_open() ).

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

注意

P_PIDFD is only available on Linux >= 5.4.

Added in version 3.3.

Added in version 3.9: The P_PIDFD 常量。

os. WCONTINUED ¶

This 选项 标志为 waitpid() , wait3() , wait4() ,和 waitid() causes child processes to be reported if they have been continued from a job control stop since they were last reported.

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

os. WEXITED ¶

This 选项 标志为 waitid() causes child processes that have terminated to be reported.

The other wait* functions always report children that have terminated, so this option is not available for them.

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

Added in version 3.3.

os. WSTOPPED ¶

This 选项 标志为 waitid() causes child processes that have been stopped by the delivery of a signal to be reported.

This option is not available for the other wait* 函数。

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

Added in version 3.3.

os. WUNTRACED ¶

This 选项 标志为 waitpid() , wait3() ,和 wait4() causes child processes to also be reported if they have been stopped but their current state has not been reported since they were stopped.

This option is not available for waitid() .

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

os. WNOHANG ¶

This 选项 flag causes waitpid() , wait3() , wait4() ,和 waitid() to return right away if no child process status is available immediately.

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

os. WNOWAIT ¶

This 选项 flag causes waitid() to leave the child in a waitable state, so that a later wait*() call can be used to retrieve the child status information again.

This option is not available for the other wait* 函数。

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

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。

Added in version 3.3.

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

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。

Added in version 3.9.

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 手册页。

Added in version 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 is restricted to.

若 pid is zero, return the set of CPUs the calling thread of the current process is restricted to.

杂项系统信息 ¶

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

Return the number of logical CPUs in the system. Returns None 若不确定。

This number is not equivalent to the number of logical CPUs the current process can use. len(os.sched_getaffinity(0)) gets the number of logical CPUs the calling thread of the current process is restricted to

Added in version 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) 了解不同标志的具体含义。

Added in version 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.

Added in version 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() .

另请参阅

The 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.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.5.2 版改变: 在 Linux,若 getrandom() syscall blocks (the urandom entropy pool is not initialized yet), fall back on reading /dev/urandom .

3.6 版改变: 在 Linux, getrandom() is now used in blocking mode to increase the security.

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 .

Added in version 3.6.

os. GRND_RANDOM ¶

若此位有设置,那么随机字节抽取自 /dev/random 池而不是 /dev/urandom 池。

Added in version 3.6.

内容表

  • os — 杂项操作系统接口
    • 文件名、命令行自变量和环境变量
    • Python UTF-8 模式
    • 进程参数
    • 文件对象创建
    • 文件描述符操作
      • 查询终端的尺寸
      • 文件描述符的继承
    • 文件和目录
      • Linux 扩展属性
    • 进程管理
    • 接口到调度器
    • 杂项系统信息
    • 随机数

上一话题

一般操作系统服务

下一话题

io — 用于操控流的核心工具

本页

  • 报告 Bug
  • 展示源

快速搜索

键入搜索术语或模块、类、函数名称。

  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 一般操作系统服务
  9. os — 杂项操作系统接口
  10. 版权所有  © 2014-2026 乐数软件    

    工业和信息化部: 粤ICP备14079481号-1