• os —- 各种各样的操作系统接口
    • 文件名,命令行参数,以及环境变量。
    • 进程参数
    • 创建文件对象
    • 文件描述符操作
      • Querying the size of a terminal
      • Inheritance of File Descriptors
    • Files and Directories
      • Linux extended attributes
    • Process Management
    • 调度器接口
    • Miscellaneous System Information
    • Random numbers

    os —- 各种各样的操作系统接口

    源代码:Lib/os.py


    本模块提供了一种使用与操作系统相关的功能的便捷式途径。 如果你只是想读写一个文件,请参阅 open(),如果你想操作文件路径,请参阅 os.path 模块,如果你想读取通过命令行给出的所有文件中的所有行,请参阅 fileinput 模块。 为了创建临时文件和目录,请参阅 tempfile 模块,对于高级文件和目录处理,请参阅 shutil 模块。

    关于这些函数的可用性的说明:

    • Python中所有依赖于操作系统的内置模块的设计都是这样,只要不同的操作系统某一相同的功能可用,它就使用相同的接口。例如,函数 os.stat(path) 以相同的格式返回关于 path 的状态信息(该格式源于 POSIX 接口)。

    • 特定于某一操作系统的扩展通过操作 os 模块也是可用的,但是使用它们当然是对可移植性的一种威胁。

    • 所有接受路径或文件名的函数都同时支持字节串和字符串对象,并在返回路径或文件名时使用相应类型的对象作为结果。

    • 在 VxWorks 系统上,os.fork, os.execv 和 os.spawnp 不被支持。

    注解

    如果使用无效或无法访问的文件名与路径,或者其他类型正确但操作系统不接受的参数,此模块的所有函数都抛出 OSError (或者它的子类)。

    • exception os.error
    • 内建的 OSError 异常的一个别名。

    • os.name

    • 导入的依赖特定操作系统的模块的名称。以下名称目前已注册: 'posix', 'nt', 'java'.

    参见

    sys.platform 有更详细的描述. os.uname() 只给出系统提供的版本信息。

    platform 模块对系统的标识有更详细的检查。

    文件名,命令行参数,以及环境变量。

    在 Python 中,使用字符串类型表示文件名、命令行参数和环境变量。 在某些系统上,在将这些字符串传递给操作系统之前,必须将这些字符串解码为字节。 Python 使用文件系统编码来执行此转换(请参阅 sys.getfilesystemencoding() )。

    在 3.1 版更改: 在某些系统上,使用文件系统编码进行转换可能会失败。 在这种情况下,Python 会使用 代理转义编码错误处理器,这意味着在解码时,不可解码的字节被 Unicode 字符 U+DCxx 替换,并且这些字节在编码时再次转换为原始字节。

    文件系统编码必须保证成功解码小于 128 的所有字节。如果文件系统编码无法提供此保证, API 函数可能会引发 UnicodeErrors 。

    进程参数

    这些函数和数据项提供了操作当前进程和用户的信息。

    • os.ctermid()
    • 返回与进程控制终端对应的文件名。

    可用性: Unix。

    • os.environ
    • 一个表示字符串环境的 mapping 对象。 例如,environ['HOME'] 是你的主目录(在某些平台上)的路径名,相当于 C 中的 getenv("HOME")

    这个映射是在第一次导入 os 模块时捕获的,通常作为 Python 启动时处理 site.py 的一部分。除了通过直接修改 os.environ 之外,在此之后对环境所做的更改不会反映在 os.environ 中。

    如果平台支持 putenv() 函数,这个映射除了可以用于查询环境外还能用于修改环境。 当这个映射被修改时,putenv() 将被自动调用。

    在Unix系统上,键和值会使用 sys.getfilesystemencoding()'surrogateescape' 的错误处理。如果你想使用其他的编码,使用 environb

    注解

    直接调用 putenv() 并不会影响 os.environ,所以推荐直接修改os.environ

    注解

    在某些平台上,包括 FreeBSD 和 Mac OS X,设置 environ 可能导致内存泄露。参阅 putenv() 的系统文档。

    如果平台没有提供 putenv(), 为了使启动的子进程使用修改后的环境,一份修改后的映射会被传给合适的进程创建函数。

    如果平台支持 unsetenv() 函数,你可以通过删除映射中元素的方式来删除对应的环境变量。当一个元素被从 os.environ 删除时,以及 pop()clear() 被调用时, unsetenv() 会被自动调用。

    • os.environb
    • 字节版本的 environ: 一个以字节串表示环境的 mapping 对象。 environenvironb 是同步的(修改 environb 会更新 environ,反之亦然)。

    只有在 supports_bytes_environTrue 的时候 environb 才是可用的。

    3.2 新版功能.

    • os.chdir(path)
    • os.fchdir(fd)
    • os.getcwd()
    • 以上函数请参阅 Files and Directories 。

    • os.fsencode(filename)

    • 编码 路径类文件名 为文件系统接受的形式,使用 'surrogateescape' 代理转义编码错误处理器,在Windows系统上会使用 'strict' ;返回 bytes 字节类型不变。

    fsdecode() 是此函数的逆向函数。

    3.2 新版功能.

    在 3.6 版更改: 增加对实现了 os.PathLike 接口的对象的支持。

    • os.fsdecode(filename)
    • 从文件系统编码方式解码为 路径类 文件名,使用 'surrogateescape' 代理转义编码错误处理器,在Windows系统上会使用 'strict' ;返回 str 字符串不变。

    fsencode() 是此函数的逆向函数。

    3.2 新版功能.

    在 3.6 版更改: 增加对实现了 os.PathLike 接口的对象的支持。

    • os.fspath(path)
    • 返回路径的文件系统表示。

    如果传入的是 strbytes 类型的字符串,将原样返回。否则 fspath() 将被调用,如果得到的是一个 strbytes 类型的对象,那就返回这个值。其他所有情况则会抛出 TypeError 异常。

    3.6 新版功能.

    • class os.PathLike
    • 描述表示一个文件系统路径的 abstract base class ,如 pathlib.PurePath

    3.6 新版功能.

    • abstractmethod fspath()
    • 返回当前对象的文件系统表示。

    这个方法只应该返回一个 str 字符串或 bytes 字节串,请优先选择 str 字符串。

    • os.getenv(key, default=None)
    • 如果存在,返回环境变量 key 的值,否则返回 defaultkeydefault 和返回值均为 str 字符串类型。

    在Unix系统上,键和值会使用 sys.getfilesystemencoding()'surrogateescape' 错误处理进行解码。如果你想使用其他的编码,使用 os.getenvb()

    可用性: 大部分的Unix系统,Windows。

    • os.getenvb(key, default=None)
    • 如果存在环境变量 key 那么返回其值,否则返回 defaultkeydefault 和返回值均为bytes字节串类型。

    getenvb() 仅在 supports_bytes_environTrue 时可用。

    可用性: 大部分的Unix系统。

    3.2 新版功能.

    • os.getexec_path(_env=None)
    • 返回将用于搜索可执行文件的目录列表,与在外壳程序中启动一个进程时相似。指定的 env 应为用于搜索 PATH 的环境变量字典。默认情况下,当 envNone 时,将会使用 environ

    3.2 新版功能.

    • os.getegid()
    • 返回当前进程的有效组ID。对应当前进程执行文件的 "set id" 位。

    可用性: Unix。

    • os.geteuid()
    • 返回当前进程的有效用户ID。

    可用性: Unix。

    • os.getgid()
    • 返回当前进程的实际组ID。

    可用性: Unix。

    • os.getgrouplist(user, group)
    • 返回该用户所在的组 ID 列表。可能 group 参数没有在返回的列表中,实际上用户应该也是属于该 groupgroup 参数一般可以从储存账户信息的密码记录文件中找到。

    可用性: Unix。

    3.3 新版功能.

    • os.getgroups()
    • 返回当前进程对应的组ID列表

    可用性: Unix。

    注解

    在Mac OS X系统中,getgroups() 会和其他 Unix 平台有些不同。如果 Python 解释器是在 10.5 或更早版本中部署,getgroups() 返回当前用户进程相关的有效组ID列表。 该列表长度由于系统预设的接口限制,最长为 16。 而且在适当的权限下,返回结果还会因 getgroups() 而发生变化;如果 Python 解释器是在 10.5 以上版本中部署,getgroups() 返回进程所属有效用户 ID 所对应的用户的组 ID 列表,组用户列表可能因为进程的生存周期而发生变动,而且也不会因为 setgroups() 的调用而发生,返回的组用户列表长度也没有长度 16 的限制。在部署中,Python 解释器用到的变量 MACOSX_DEPLOYMENT_TARGET 可以用 sysconfig.get_config_var()

    • os.getlogin()
    • 返回通过控制终端进程进行登录的用户名。在多数情况下,使用 getpass.getuser() 会更有效,因为后者会通过检查环境变量 LOGNAMEUSERNAME 来查找用户,再由 pwd.getpwuid(os.getuid())[0] 来获取当前用户 ID 的登录名。

    可用性: Unix, Windows。

    • os.getpgid(pid)
    • 根据进程id pid 返回进程的组 ID 列表。如果 pid 为 0,则返回当前进程的进程组 ID 列表

    可用性: Unix。

    • os.getpgrp()
    • 返回当时进程组的ID

    可用性: Unix。

    • os.getpid()
    • 返回当前进程ID

    • os.getppid()

    • 返回父进程ID。当父进程已经结束,在Unix中返回的ID是初始进程(1)中的一个,在Windows中仍然是同一个进程ID,该进程ID有可能已经被进行进程所占用。

    可用性: Unix, Windows。

    在 3.2 版更改: 添加WIndows的支持。

    • os.getpriority(which, who)
    • 获取程序调度优先级。which 参数值可以是 PRIO_PROCESSPRIO_PGRP,或 PRIO_USER 中的一个,who 是相对于 which (PRIO_PROCESS 的进程标识符,PRIO_PGRP 的进程组标识符和 PRIO_USER 的用户ID)。当 who 为 0 时(分别)表示调用的进程,调用进程的进程组或调用进程所属的真实用户 ID。

    可用性: Unix。

    3.3 新版功能.

    • os.PRIO_PROCESS
    • os.PRIO_PGRP
    • os.PRIO_USER
    • 函数 getpriority()setpriority() 的参数。

    可用性: Unix。

    3.3 新版功能.

    • os.getresuid()
    • 返回一个由 (ruid, euid, suid) 所组成的元组,分别表示当前进程的真实用户ID,有效用户ID和甲暂存用户ID。

    可用性: Unix。

    3.2 新版功能.

    • os.getresgid()
    • 返回一个由 (rgid, egid, sgid) 所组成的元组,分别表示当前进程的真实组ID,有效组ID和暂存组ID。

    可用性: Unix。

    3.2 新版功能.

    • os.getuid()
    • 返回当前进程的真实用户ID。

    可用性: Unix。

    • os.initgroups(username, gid)
    • 调用系统 initgroups(),使用指定用户所在的所有值来初始化组访问列表,包括指定的组ID。

    可用性: Unix。

    3.2 新版功能.

    • os.putenv(key, value)
    • 将名为 key 的环境变量值设置为 value。该变量名修改会影响由 os.system()popen()fork()execv() 发起的子进程。

    可用性: 大部分的Unix系统,Windows。

    注解

    在一些平台,包括 FreeBSD 和 Mac OS X,设置 environ 可能导致内存泄露。详情参考 putenv 相关系统文档。

    当系统支持 putenv() 时,os.environ 中的参数赋值会自动转换为对 putenv() 的调用。不过 putenv() 的调用不会更新 os.environ,因此最好使用 os.environ 对变量赋值。

    • os.setegid(egid)
    • 设置当前进程的有效组ID。

    可用性: Unix。

    • os.seteuid(euid)
    • 设置当前进程的有效用户ID。

    可用性: Unix。

    • os.setgid(gid)
    • 设置当前进程的组ID。

    可用性: Unix。

    • os.setgroups(groups)
    • group 参数值设置为与当进程相关联的附加组ID列表。group 参数必须为一个序列,每个元素应为每个组的数字ID。该操作通常只适用于超级用户。

    可用性: Unix。

    注解

    在 Mac OS X 中,groups 的长度不能超过系统定义的最大有效组 ID 个数,一般为 16。 如果它没有返回与调用 setgroups() 所设置的相同的组列表,请参阅 getgroups() 的文档。

    • os.setpgrp()
    • 根据已实现的版本(如果有)来调用系统 setpgrp()setpgrp(0, 0) 。相关说明,请参考 Unix 手册。

    可用性: Unix。

    • os.setpgid(pid, pgrp)
    • 使用系统调用 setpgid(),将 pid 对应进程的组ID设置为 pgrp。相关说明,请参考 Unix 手册。

    可用性: Unix。

    • os.setpriority(which, who, priority)
    • 设置程序调度优先级。 which 的值为 PRIO_PROCESS, PRIO_PGRPPRIO_USER 之一,而 who 会相对于 which (PRIO_PROCESS 的进程标识符, PRIO_PGRP 的进程组标识符和 PRIO_USER 的用户 ID) 被解析。 who 值为零 (分别) 表示调用进程,调用进程的进程组或调用进程的真实用户 ID。 priority 是范围在 -20 至 19 的值。 默认优先级为 0;较小的优先级数值会更优先被调度。

    可用性: Unix。

    3.3 新版功能.

    • os.setregid(rgid, egid)
    • 设置当前进程的真实和有效组ID。

    可用性: Unix。

    • os.setresgid(rgid, egid, sgid)
    • 设置当前进程的真实,有效和暂存组ID。

    可用性: Unix。

    3.2 新版功能.

    • os.setresuid(ruid, euid, suid)
    • 设置当前进程的真实,有效和暂存用户ID。

    可用性: Unix。

    3.2 新版功能.

    • os.setreuid(ruid, euid)
    • 设置当前进程的真实和有效用户ID。

    可用性: Unix。

    • os.getsid(pid)
    • 调用系统调用 getsid()。相关说明,请参考 Unix 手册。

    可用性: Unix。

    • os.setsid()
    • 使用系统调用 getsid()。相关说明,请参考 Unix 手册。

    可用性: Unix。

    • os.setuid(uid)
    • 设置当前进程的用户ID。

    可用性: Unix。

    • os.strerror(code)
    • 根据 code 中的错误码返回错误消息。 在某些平台上当给出未知错误码时 strerror() 将返回 NULL 并会引发 ValueError

    • os.supports_bytes_environ

    • 如果操作系统上原生环境类型是字节型则为 True (例如在 Windows 上为 False)。

    3.2 新版功能.

    • os.umask(mask)
    • 设定当前数值掩码并返回之前的掩码。

    • os.uname()

    • 返回当前操作系统的识别信息。返回值是一个有5个属性的对象:

      • sysname - 操作系统名

      • nodename - 机器在网络上的名称(需要先设定)

      • release - 操作系统发行信息

      • version - 操作系统版本信息

      • machine - 硬件标识符

    为了向后兼容,该对象也是可迭代的,像是一个按照 sysnamenodenamereleaseversion,和 machine 顺序组成的元组。

    有些系统会将 nodename 截短为 8 个字符或截短至前缀部分;获取主机名的一个更好方式是 socket.gethostname() 或甚至可以用 socket.gethostbyaddr(socket.gethostname())

    可用性: 较新的 Unix 版本。

    在 3.3 版更改: 返回结果的类型由元组变成一个类似元组的对象,同时具有命名的属性。

    • os.unsetenv(key)
    • 取消设置(删除)名为 key 的环境变量。变量名的改变会影响由 os.system()popen()fork()execv() 触发的子进程。

    当系统支持 unsetenv() ,删除在 os.environ 中的变量会自动转换为对 unsetenv() 的调用。但是 unsetenv() 不能更新 os.environ,因此最好直接删除 os.environ 中的变量。

    可用性: 大部分的Unix系统,Windows。

    创建文件对象

    这些函数创建新的 file objects 。(参见 open() 以获取打开文件描述符的相关信息。)

    • os.fdopen(fd, *args, **kwargs)
    • 返回打开文件描述符 fd 对应文件的对象。类似内建 open() 函数,二者接受同样的参数。不同之处在于 fdopen() 第一个参数应该为整数。

    文件描述符操作

    这些函数对文件描述符所引用的 I/O 流进行操作。

    文件描述符是一些小的整数,对应于当前进程所打开的文件。例如,标准输入的文件描述符通常是0,标准输出是1,标准错误是2。之后被进程打开的文件的文件描述符会被依次指定为3,4,5等。“文件描述符”这个词有点误导性,在 Unix 平台中套接字和管道也被文件描述符所引用。

    当需要时,可以用 fileno() 可以获得 file object 所对应的文件描述符。需要注意的是,直接使用文件描述符会绕过文件对象的方法,会忽略如数据内部缓冲等情况。

    • os.close(fd)
    • 关闭文件描述符 fd

    注解

    该功能适用于低级 I/O 操作,必须用于 os.open()pipe() 返回的文件描述符。关闭由内建函数 open()popen()fdopen() 返回的 "文件对象",则使用其相应的 close() 方法。

    • os.closerange(fd_low, fd_high)
    • 关闭从 fd_low (包括)到 fd_high (排除)间的文件描述符,并忽略错误。类似(但快于):
    1. for fd in range(fd_low, fd_high):
    2. try:
    3. os.close(fd)
    4. except OSError:
    5. pass
    • os.copyfile_range(_src, dst, count, offset_src=None, offset_dst=None)
    • 从文件描述符 src 复制 count 字节,从偏移量 offset_src 开始读取,到文件描述符 dst,从偏移量 offset_dst 开始写入。如果 offset_src 为 None,则 src 将从当前位置开始读取;offset_dst 同理。srcdst 指向的文件必须处于相同的文件系统,否则将会抛出一个 errno 被设为 errno.EXDEVOSError

    此复制的完成没有额外的从内核到用户空间再回到内核的数据转移花费。另外,一些文件系统可能实现额外的优化。完成复制就如同打开两个二进制文件一样。

    返回值是复制的字节的数目。这可能低于需求的数目。

    Availability: Linux kernel >= 4.5 或 glibc >= 2.27。

    3.8 新版功能.

    • os.deviceencoding(_fd)
    • 如果连接到终端,则返回一个与 fd 关联的设备描述字符,否则返回 None

    • os.dup(fd)

    • 返回一个文件描述符 fd 的副本。该文件描述符的副本是 不可继承的。

    在 Windows 中,当复制一个标准流(0: stdin, 1: stdout, 2: stderr)时,新的文件描述符是 可继承的。

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

    • os.dup2(fd, fd2, inheritable=True)
    • 把文件描述符 fd 复制为 fd2,必要时先关闭后者。返回 fd2。新的文件描述符默认是 可继承的,除非在 inheritableFalse 时,是不可继承的。

    在 3.4 版更改: 添加可选参数 inheritable

    在 3.7 版更改: 成功时返回 fd2,以过去的版本中,总是返回 None

    • os.fchmod(fd, mode)
    • fd 指定文件的权限状态修改为 mode。可以参考 chmod() 中列出 mode 的可用值。从Python 3.3开始,这相当于 os.chmod(fd, mode)

    可用性: Unix。

    • os.fchown(fd, uid, gid)
    • 分别将 fd 指定文件的所有者和组 ID 修改为 uidgid 的值。若不想变更其中的某个 ID,可将相应值设为 -1。参考 chown()。从 Python 3.3 开始,这相当于 os.chown(fd, uid, gid)

    可用性: Unix。

    • os.fdatasync(fd)
    • 强制将文件描述符 fd 指定文件写入磁盘。不强制更新元数据。

    可用性: Unix。

    注解

    该功能在 MacOS 中不可用。

    • os.fpathconf(fd, name)
    • 返回与打开的文件有关的系统配置信息。name 指定要查找的配置名称,它可以是字符串,是一个系统已定义的名称,这些名称定义在不同标准(POSIX.1,Unix 95,Unix 98 等)中。一些平台还定义了额外的其他名称。当前操作系统已定义的名称在 pathconfnames 字典中给出。对于未包含在该映射中的配置名称,也可以传递一个整数作为 _name

    如果 name 是一个字符串且不是已定义的名称,将抛出 ValueError 异常。如果当前系统不支持 name 指定的配置名称,即使该名称存在于 pathconf_names,也会抛出 OSError 异常,错误码为 errno.EINVAL

    从 Python 3.3 起,此功能等价于 os.pathconf(fd, name)

    可用性: Unix。

    • os.fstat(fd)
    • 获取文件描述符 fd 的状态. 返回一个 stat_result 对象。

    从 Python 3.3 起,此功能等价于 os.stat(fd)

    参见

    stat() 函数。

    • os.fstatvfs(fd)
    • 返回文件系统的信息,该文件系统是文件描述符 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.getblocking(_fd)
    • 获取文件描述符的阻塞模式:如果设置了 O_NONBLOCK 标志位,返回 False,如果该标志位被清除,返回 True

    参见 set_blocking()socket.socket.setblocking()

    可用性: Unix。

    3.5 新版功能.

    • os.isatty(fd)
    • 如果文件描述符 fd 打开且已连接至 tty 设备(或类 tty 设备),返回 True,否则返回 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.

    可用性: Unix。

    3.3 新版功能.

    • os.F_LOCK
    • os.F_TLOCK
    • os.F_ULOCK
    • os.F_TEST
    • Flags that specify what action lockf() will take.

    可用性: Unix。

    3.3 新版功能.

    • os.lseek(fd, pos, how)
    • Set the current position of file descriptor fd to position pos, modifiedby how: SEEK_SET or 0 to set the position relative to thebeginning of the file; SEEK_CUR or 1 to set it relative to thecurrent position; SEEK_END or 2 to set it relative to the end ofthe file. Return the new cursor position in bytes, starting from the beginning.

    • os.SEEK_SET

    • os.SEEK_CUR
    • os.SEEK_END
    • Parameters to the lseek() function. Their values are 0, 1, and 2,respectively.

    3.3 新版功能: Some operating systems could support additional values, likeos.SEEK_HOLE or os.SEEK_DATA.

    • os.open(path, flags, mode=0o777, *, dir_fd=None)
    • Open the file path and set various flags according to flags and possiblyits mode according to mode. When computing mode, the current umask valueis first masked out. Return the file descriptor for the newly opened file.The new file descriptor is non-inheritable.

    For a description of the flag and mode values, see the C run-time documentation;flag constants (like O_RDONLY and O_WRONLY) are defined inthe os module. In particular, on Windows addingO_BINARY is needed to open files in binary mode.

    This function can support paths relative to directory descriptors with the dir_fd parameter.

    引发一个 审核事件 open 附带参数 pathmodeflags

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

    注解

    This function is intended for low-level I/O. For normal usage, use thebuilt-in function open(), which returns a file object withread() and write() methods (and many more). Towrap a file descriptor in a file object, use fdopen().

    3.3 新版功能: dir_fd 参数。

    在 3.5 版更改: 如果系统调用被中断,但信号处理程序没有触发异常,此函数现在会重试系统调用,而不是触发 InterruptedError 异常 (原因详见 PEP 475)。

    在 3.6 版更改: 接受一个 类路径对象。

    The following constants are options for the flags parameter to theopen() function. They can be combined using the bitwise OR operator|. Some of them are not available on all platforms. For descriptions oftheir availability and use, consult the open(2)) manual page on Unixor the MSDN on Windows.

    • os.O_RDONLY
    • os.O_WRONLY
    • os.O_RDWR
    • os.O_APPEND
    • os.O_CREAT
    • os.O_EXCL
    • os.O_TRUNC
    • The above constants are available on Unix and 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 版更改: Add O_CLOEXEC constant.

    • 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_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
    • The above constants are extensions and not present if they are not defined bythe C library.

    在 3.4 版更改: Add O_PATH on systems that support it.Add O_TMPFILE, only available on Linux Kernel 3.11 or newer.

    • os.openpty()
    • Open a new pseudo-terminal pair. Return a pair of file descriptors(master, slave) for the pty and the tty, respectively. The new filedescriptors are non-inheritable. For a (slightly) moreportable approach, use the pty module.

    可用性: 某些 Unix。

    在 3.4 版更改: 新的文件描述符不再可继承。

    • os.pipe()
    • Create a pipe. Return a pair of file descriptors (r, w) usable forreading and writing, respectively. The new file descriptor isnon-inheritable.

    可用性: Unix, Windows。

    在 3.4 版更改: 新的文件描述符不再可继承。

    • os.pipe2(flags)
    • Create a pipe with flags set atomically.flags can be constructed by ORing together one or more of these values:O_NONBLOCK, O_CLOEXEC.Return a pair of file descriptors (r, w) usable for reading and writing,respectively.

    可用性: 某些 Unix。

    3.3 新版功能.

    • os.posixfallocate(_fd, offset, len)
    • Ensures that enough disk space is allocated for the file specified by fd_starting from _offset and continuing for len bytes.

    可用性: Unix。

    3.3 新版功能.

    • os.posixfadvise(_fd, offset, len, advice)
    • Announces an intention to access data in a specific pattern thus allowingthe kernel to make optimizations.The advice applies to the region of the file specified by fd starting atoffset and continuing for len bytes.advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE,POSIX_FADV_WILLNEED or POSIX_FADV_DONTNEED.

    可用性: Unix。

    3.3 新版功能.

    • os.POSIX_FADV_NORMAL
    • os.POSIX_FADV_SEQUENTIAL
    • os.POSIX_FADV_RANDOM
    • os.POSIX_FADV_NOREUSE
    • os.POSIX_FADV_WILLNEED
    • os.POSIX_FADV_DONTNEED
    • Flags that can be used in advice in posix_fadvise() that specifythe access pattern that is likely to be used.

    可用性: Unix。

    3.3 新版功能.

    • os.pread(fd, n, offset)
    • Read at most n bytes from file descriptor fd at a position of offset,leaving the file offset unchanged.

    Return a bytestring containing the bytes read. If the end of the filereferred to by fd has been reached, an empty bytes object is returned.

    可用性: Unix。

    3.3 新版功能.

    • os.preadv(fd, buffers, offset, flags=0)
    • Read from a file descriptor fd at a position of offset into mutablebytes-like objectsbuffers, leaving the fileoffset unchanged. Transfer data into each buffer until it is full and thenmove 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 followingflags:

    • RWF_HIPRI

    • RWF_NOWAIT

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

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

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

    Availability: Linux 2.6.30 and newer, FreeBSD 6.0 and newer,OpenBSD 2.7 and newer. Using flags requires Linux 4.6 or newer.

    3.7 新版功能.

    • os.RWF_NOWAIT
    • Do not wait for data which is not immediately available. If this flag isspecified, the system call will return instantly if it would have to readdata 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 toerrno.EAGAIN.

    Availability: Linux 4.14 and newer.

    3.7 新版功能.

    • os.RWF_HIPRI
    • High priority read/write. Allows block-based filesystems to use pollingof the device, which provides lower latency, but may use additionalresources.

    Currently, on Linux, this feature is usable only on a file descriptor openedusing the O_DIRECT flag.

    Availability: Linux 4.6 and newer.

    3.7 新版功能.

    • os.pwrite(fd, str, offset)
    • Write the bytestring in str to file descriptor fd at position ofoffset, leaving the file offset unchanged.

    Return the number of bytes actually written.

    可用性: Unix。

    3.3 新版功能.

    • os.pwritev(fd, buffers, offset, flags=0)
    • Write the buffers contents to file descriptor fd at a offset offset,leaving the file offset unchanged. buffers must be a sequence ofbytes-like objects. Buffers are processed inarray order. Entire contents of the first buffer is written beforeproceeding to the second, and so on.

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

    • RWF_DSYNC

    • RWF_SYNC

    Return the total number of bytes actually written.

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

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

    Availability: Linux 2.6.30 and newer, FreeBSD 6.0 and newer,OpenBSD 2.7 and newer. Using flags requires Linux 4.7 or newer.

    3.7 新版功能.

    • os.RWF_DSYNC
    • Provide a per-write equivalent of the O_DSYNC open(2) flag. Thisflag effect applies only to the data range written by the system call.

    Availability: Linux 4.7 and newer.

    3.7 新版功能.

    • os.RWF_SYNC
    • Provide a per-write equivalent of the O_SYNC open(2) flag. Thisflag effect applies only to the data range written by the system call.

    Availability: Linux 4.7 and newer.

    3.7 新版功能.

    • os.read(fd, n)
    • Read at most n bytes from file descriptor fd.

    Return a bytestring containing the bytes read. If the end of the filereferred to by fd has been reached, an empty bytes object is returned.

    注解

    This function is intended for low-level I/O and must be applied to a filedescriptor as returned by os.open() or pipe(). To read a"file object" returned by the built-in function open() or bypopen() or fdopen(), or sys.stdin, use itsread() or readline() methods.

    在 3.5 版更改: 如果系统调用被中断,但信号处理程序没有触发异常,此函数现在会重试系统调用,而不是触发 InterruptedError 异常 (原因详见 PEP 475)。

    • os.sendfile(out, in, offset, count)
    • os.sendfile(out, in, offset, count, [headers, ][trailers, ]flags=0)
    • Copy count bytes from file descriptor in to file descriptor out_starting at _offset.Return the number of bytes sent. When EOF is reached return 0.

    The first function notation is supported by all platforms that definesendfile().

    On Linux, if offset is given as None, the bytes are read from thecurrent position of in and the position of in is updated.

    The second case may be used on Mac OS X and FreeBSD where headers andtrailers are arbitrary sequences of buffers that are written before andafter the data from in is written. It returns the same as the first case.

    On Mac OS X and FreeBSD, a value of 0 for count specifies to send untilthe end of in is reached.

    All platforms support sockets as out file descriptor, and some platformsallow other types (e.g. regular file, pipe) as well.

    Cross-platform applications should not use headers, trailers and _flags_arguments.

    可用性: Unix。

    注解

    For a higher-level wrapper of sendfile(), seesocket.socket.sendfile().

    3.3 新版功能.

    • os.setblocking(_fd, blocking)
    • Set the blocking mode of the specified file descriptor. Set theO_NONBLOCK flag if blocking is False, clear the flag otherwise.

    See also get_blocking() and socket.socket.setblocking().

    可用性: Unix。

    3.5 新版功能.

    • os.SF_NODISKIO
    • os.SF_MNOWAIT
    • os.SF_SYNC
    • Parameters to the sendfile() function, if the implementation supportsthem.

    可用性: Unix。

    3.3 新版功能.

    • os.readv(fd, buffers)
    • Read from a file descriptor fd into a number of mutable bytes-likeobjectsbuffers. Transfer data into each buffer untilit is full and then move on to the next buffer in the sequence to hold therest of the data.

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

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

    可用性: Unix。

    3.3 新版功能.

    • os.tcgetpgrp(fd)
    • Return the process group associated with the terminal given by fd (an openfile descriptor as returned by os.open()).

    可用性: Unix。

    • os.tcsetpgrp(fd, pg)
    • Set the process group associated with the terminal given by fd (an open filedescriptor as returned by os.open()) to pg.

    可用性: Unix。

    • os.ttyname(fd)
    • Return a string which specifies the terminal device associated withfile descriptor fd. If fd is not associated with a terminal device, anexception is raised.

    可用性: Unix。

    • os.write(fd, str)
    • Write the bytestring in str to file descriptor fd.

    Return the number of bytes actually written.

    注解

    This function is intended for low-level I/O and must be applied to a filedescriptor as returned by os.open() or pipe(). To write a "fileobject" returned by the built-in function open() or by popen() orfdopen(), or sys.stdout or sys.stderr, use itswrite() method.

    在 3.5 版更改: 如果系统调用被中断,但信号处理程序没有触发异常,此函数现在会重试系统调用,而不是触发 InterruptedError 异常 (原因详见 PEP 475)。

    • os.writev(fd, buffers)
    • Write the contents of buffers to file descriptor fd. buffers must bea sequence of bytes-like objects. Buffers areprocessed in array order. Entire contents of the first buffer is writtenbefore proceeding to the second, and so on.

    Returns the total number of bytes actually written.

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

    可用性: Unix。

    3.3 新版功能.

    Querying the size of a terminal

    3.3 新版功能.

    • os.getterminal_size(_fd=STDOUT_FILENO)
    • Return the size of the terminal window as (columns, lines),tuple of type terminal_size.

    The optional argument fd (default STDOUT_FILENO, or standardoutput) specifies which file descriptor should be queried.

    If the file descriptor is not connected to a terminal, an OSErroris raised.

    shutil.get_terminal_size() is the high-level function whichshould normally be used, os.get_terminal_size is the low-levelimplementation.

    可用性: Unix, Windows。

    • class os.terminal_size
    • A subclass of tuple, holding (columns, lines) of the terminal window size.

      • columns
      • Width of the terminal window in characters.

      • lines

      • Height of the terminal window in characters.

    Inheritance of File Descriptors

    3.4 新版功能.

    A file descriptor has an "inheritable" flag which indicates if the file descriptorcan be inherited by child processes. Since Python 3.4, file descriptorscreated by Python are non-inheritable by default.

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

    On Windows, non-inheritable handles and file descriptors are closed in childprocesses, except for standard streams (file descriptors 0, 1 and 2: stdin, stdoutand 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 standardstreams are closed, and inheritable handles are only inherited if theclose_fds parameter is False.

    • os.getinheritable(_fd)
    • Get the "inheritable" flag of the specified file descriptor (a boolean).

    • os.setinheritable(_fd, inheritable)

    • Set the "inheritable" flag of the specified file descriptor.

    • os.gethandle_inheritable(_handle)

    • Get the "inheritable" flag of the specified handle (a boolean).

    可用性: Windows。

    • os.sethandle_inheritable(_handle, inheritable)
    • Set the "inheritable" flag of the specified handle.

    可用性: Windows。

    Files and Directories

    On some Unix platforms, many of these functions support one or more of thesefeatures:

    • specifying a file descriptor:Normally the path argument provided to functions in the os modulemust be a string specifying a file path. However, some functions nowalternatively 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 prefixedwith f (e.g. call fchdir instead of chdir).)

    You can check whether or not path can be specified as a file descriptorfor a particular function on your platform using os.supports_fd.If this functionality is unavailable, using it will raise aNotImplementedError.

    If the function also supports dir_fd or follow_symlinks arguments, it'san error to specify one of those when supplying path as a file descriptor.

    • paths relative to directory descriptors: If dir_fd is not None, itshould be a file descriptor referring to a directory, and the path to operateon should be relative; path will then be relative to that directory. If thepath is absolute, dir_fd is ignored. (For POSIX systems, Python will callthe variant of the function with an at suffix and possibly prefixed withf (e.g. call faccessat instead of access).

    You can check whether or not dir_fd is supported for a particular functionon your platform using os.supports_dir_fd. If it's unavailable,using it will raise a NotImplementedError.

    • not following symlinks: If follow_symlinks isFalse, 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 filepointed 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 particularfunction 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 operationswill use the effective uid/gid, therefore this routine can be used in asuid/sgid environment to test if the invoking user has the specified access topath. mode should be F_OK to test the existence of path, or itcan be the inclusive OR of one or more of R_OK, W_OK, andX_OK to test permissions. Return True if access is allowed,False if not. See the Unix man page access(2)) for moreinformation.

    This function can support specifying paths relative to directorydescriptors and not following symlinks.

    If effective_ids is True, access() will perform its accesschecks using the effective uid/gid instead of the real uid/gid.effective_ids may not be supported on your platform; you can check whetheror not it is available using os.supports_effective_ids. If it isunavailable, using it will raise a NotImplementedError.

    注解

    Using access() to check if a user is authorized to e.g. open a filebefore actually doing so using open() creates a security hole,because the user might exploit the short time interval between checkingand opening the file to manipulate it. It's preferable to use EAFPtechniques. For example:

    1. if os.access("myfile", os.R_OK):
    2. with open("myfile") as fp:
    3. return fp.read()
    4. return "some default data"

    is better written as:

    1. try:
    2. fp = open("myfile")
    3. except PermissionError:
    4. return "some default data"
    5. else:
    6. with fp:
    7. return fp.read()

    注解

    I/O operations may fail even when access() indicates that they wouldsucceed, particularly for operations on network filesystems which may havepermissions semantics beyond the usual POSIX permission-bit model.

    在 3.3 版更改: Added the dir_fd, effective_ids, and follow_symlinks parameters.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.F_OK
    • os.R_OK
    • os.W_OK
    • os.X_OK
    • Values to pass as the mode parameter of access() to test theexistence, readability, writability and executability of path,respectively.

    • os.chdir(path)

    • Change the current working directory to path.

    This function can support specifying a file descriptor. Thedescriptor must refer to an opened directory, not an open file.

    This function can raise OSError and subclasses such asFileNotFoundError, PermissionError, and NotADirectoryError.

    3.3 新版功能: Added support for specifying path as a file descriptoron some platforms.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.chflags(path, flags, *, follow_symlinks=True)
    • Set the flags of path to the numeric flags. flags may take a combination(bitwise OR) of the following values (as defined in the stat module):

      • 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

    This function can support not following symlinks.

    可用性: Unix。

    3.3 新版功能: The follow_symlinks argument.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
    • Change the mode of path to the numeric mode. mode may take one of thefollowing values (as defined in the stat module) or bitwise ORedcombinations 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

    This function can support specifying a file descriptor,paths relative to directory descriptors and notfollowing symlinks.

    注解

    Although Windows supports chmod(), you can only set the file'sread-only flag with it (via the stat.S_IWRITE and stat.S_IREADconstants or a corresponding integer value). All other bits are ignored.

    3.3 新版功能: Added support for specifying path as an open file descriptor,and the dir_fd and follow_symlinks arguments.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)
    • Change the owner and group id of path to the numeric uid and gid. Toleave one of the ids unchanged, set it to -1.

    This function can support specifying a file descriptor,paths relative to directory descriptors and notfollowing symlinks.

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

    可用性: Unix。

    3.3 新版功能: Added support for specifying path as an open file descriptor,and the dir_fd and follow_symlinks arguments.

    在 3.6 版更改: Supports a path-like object.

    • os.chroot(path)
    • Change the root directory of the current process to path.

    可用性: Unix。

    在 3.6 版更改: 接受一个 类路径对象。

    • os.fchdir(fd)
    • Change the current working directory to the directory represented by the filedescriptor fd. The descriptor must refer to an opened directory, not anopen file. As of Python 3.3, this is equivalent to os.chdir(fd).

    可用性: Unix。

    • os.getcwd()
    • Return a string representing the current working directory.

    • 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 ANSIcode page: see PEP 529 for the rationale. The function is no longerdeprecated on Windows.

    • os.lchflags(path, flags)
    • Set the flags of path to the numeric flags, like chflags(), but donot follow symbolic links. As of Python 3.3, this is equivalent toos.chflags(path, flags, follow_symlinks=False).

    可用性: Unix。

    在 3.6 版更改: 接受一个 类路径对象。

    • os.lchmod(path, mode)
    • Change the mode of path to the numeric mode. If path is a symlink, thisaffects the symlink rather than the target. See the docs for chmod()for possible values of mode. As of Python 3.3, this is equivalent toos.chmod(path, mode, follow_symlinks=False).

    可用性: Unix。

    在 3.6 版更改: 接受一个 类路径对象。

    • os.lchown(path, uid, gid)
    • Change the owner and group id of path to the numeric uid and gid. Thisfunction will not follow symbolic links. As of Python 3.3, this is equivalentto os.chown(path, uid, gid, follow_symlinks=False).

    可用性: Unix。

    在 3.6 版更改: 接受一个 类路径对象。

    • os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)
    • Create a hard link pointing to src named dst.

    This function can support specifying src_dir_fd and/or dst_dir_fd tosupply paths relative to directory descriptors, and notfollowing symlinks.

    可用性: Unix, Windows。

    在 3.2 版更改: 添加了Windows 支持

    3.3 新版功能: Added the src_dir_fd, dst_dir_fd, and follow_symlinks arguments.

    在 3.6 版更改: Accepts a path-like object for src and dst.

    • os.listdir(path='.')
    • Return a list containing the names of the entries in the directory given bypath. The list is in arbitrary order, and does not include the specialentries '.' and '..' even if they are present in the directory.

    path may be a path-like object. If path is of type bytes(directly or indirectly through the PathLike interface),the filenames returned will also be of type bytes;in all other circumstances, they will be of type str.

    This function can also support specifying a file descriptor; the file descriptor must refer to a directory.

    Raises an auditing event os.listdir with argument path.

    注解

    To encode str filenames to bytes, use fsencode().

    参见

    The scandir() function returns directory entries along withfile attribute information, giving better performance for manycommon use cases.

    在 3.2 版更改: The path parameter became optional.

    3.3 新版功能: Added support for specifying path as an open file descriptor.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.lstat(path, *, dir_fd=None)
    • Perform the equivalent of an lstat() system call on the given path.Similar to stat(), but does not follow symbolic links. Return astat_result object.

    On platforms that do not support symbolic links, this is an alias forstat().

    As of Python 3.3, this is equivalent to os.stat(path, dir_fd=dir_fd,follow_symlinks=False).

    This function can also support paths relative to directory descriptors.

    参见

    stat() 函数。

    在 3.2 版更改: Added support for Windows 6.0 (Vista) symbolic links.

    在 3.3 版更改: Added the dir_fd parameter.

    在 3.6 版更改: Accepts a path-like object for src and dst.

    在 3.8 版更改: On Windows, now opens reparse points that represent another path(name surrogates), including symbolic links and directory junctions.Other kinds of reparse points are resolved by the operating system asfor stat().

    • os.mkdir(path, mode=0o777, *, dir_fd=None)
    • Create a directory named path with numeric mode mode.

    If the directory already exists, FileExistsError is raised.

    On some systems, mode is ignored. Where it is used, the current umaskvalue is first masked out. If bits other than the last 9 (i.e. the last 3digits of the octal representation of the mode) are set, their meaning isplatform-dependent. On some platforms, they are ignored and you should callchmod() explicitly to set them.

    This function can also support paths relative to directory descriptors.

    It is also possible to create temporary directories; see thetempfile module's tempfile.mkdtemp() function.

    3.3 新版功能: dir_fd 参数。

    在 3.6 版更改: 接受一个 类路径对象。

    • os.makedirs(name, mode=0o777, exist_ok=False)
    • Recursive directory creation function. Like mkdir(), but makes allintermediate-level directories needed to contain the leaf directory.

    The mode parameter is passed to mkdir() for creating the leafdirectory; see the mkdir() description for how itis interpreted. To set the file permission bits of any newly-created parentdirectories you can set the umask before invoking makedirs(). Thefile permission bits of existing parent directories are not changed.

    If exist_ok is False (the default), an FileExistsError israised if the target directory already exists.

    注解

    makedirs() will become confused if the path elements to createinclude pardir (eg. ".." on UNIX systems).

    This function handles UNC paths correctly.

    3.2 新版功能: The exist_ok parameter.

    在 3.4.1 版更改: Before Python 3.4.1, if exist_ok was True and the directory existed,makedirs() would still raise an error if mode did not match themode of the existing directory. Since this behavior was impossible toimplement safely, it was removed in Python 3.4.1. See bpo-21082.

    在 3.6 版更改: 接受一个 类路径对象。

    在 3.7 版更改: The mode argument no longer affects the file permission bits ofnewly-created intermediate-level directories.

    • os.mkfifo(path, mode=0o666, *, dir_fd=None)
    • Create a FIFO (a named pipe) named path with numeric mode mode.The current umask value is first masked out from the mode.

    This function can also support paths relative to directory descriptors.

    FIFOs are pipes that can be accessed like regular files. FIFOs exist until theyare deleted (for example with os.unlink()). Generally, FIFOs are used asrendezvous between "client" and "server" type processes: the server opens theFIFO for reading, and the client opens it for writing. Note that mkfifo()doesn't open the FIFO —- it just creates the rendezvous point.

    可用性: Unix。

    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) namedpath. mode specifies both the permissions to use and the type of nodeto be created, being combined (bitwise OR) with one of stat.SIFREG,stat.S_IFCHR, stat.S_IFBLK, and stat.S_IFIFO (those constants areavailable in stat). For stat.S_IFCHR and stat.S_IFBLK,_device defines the newly created device special file (probably usingos.makedev()), otherwise it is ignored.

    This function can also support paths relative to directory descriptors.

    可用性: Unix。

    3.3 新版功能: dir_fd 参数。

    在 3.6 版更改: 接受一个 类路径对象。

    • os.major(device)
    • Extract the device major number from a raw device number (usually thest_dev or st_rdev field from stat).

    • os.minor(device)

    • Extract the device minor number from a raw device number (usually thest_dev or st_rdev field from 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 thename of a defined system value; these names are specified in a number ofstandards (POSIX.1, Unix 95, Unix 98, and others). Some platforms defineadditional names as well. The names known to the host operating system aregiven in the pathconf_names dictionary. For configuration variables notincluded in that mapping, passing an integer for _name is also accepted.

    如果 name 是一个字符串且不是已定义的名称,将抛出 ValueError 异常。如果当前系统不支持 name 指定的配置名称,即使该名称存在于 pathconf_names,也会抛出 OSError 异常,错误码为 errno.EINVAL

    This function can support specifying a file descriptor.

    可用性: Unix。

    在 3.6 版更改: 接受一个 类路径对象。

    • os.pathconf_names
    • Dictionary mapping names accepted by pathconf() and fpathconf() tothe integer values defined for those names by the host operating system. Thiscan be used to determine the set of names known to the system.

    可用性: Unix。

    • os.readlink(path, *, dir_fd=None)
    • Return a string representing the path to which the symbolic link points. Theresult may be either an absolute or relative pathname; if it is relative, itmay be converted to an absolute pathname usingos.path.join(os.path.dirname(path), result).

    If the path is a string object (directly or indirectly through aPathLike interface), the result will also be a string object,and the call may raise a UnicodeDecodeError. If the path is a bytesobject (direct or indirectly), the result will be a bytes object.

    This function can also support paths relative to directory descriptors.

    When trying to resolve a path that may contain links, userealpath() to properly handle recursion and platformdifferences.

    可用性: Unix, Windows。

    在 3.2 版更改: Added support for Windows 6.0 (Vista) symbolic links.

    3.3 新版功能: dir_fd 参数。

    在 3.6 版更改: Accepts a path-like object on Unix.

    在 3.8 版更改: Accepts a path-like object and a bytes object on Windows.

    在 3.8 版更改: Added support for directory junctions, and changed to return thesubstitution path (which typically includes \?\ prefix) ratherthan the optional "print name" field that was previously returned.

    • os.remove(path, *, dir_fd=None)
    • Remove (delete) the file path. If path is a directory, anIsADirectoryError is raised. Use rmdir() to remove directories.

    This function can support paths relative to directory descriptors.

    On Windows, attempting to remove a file that is in use causes an exception tobe raised; on Unix, the directory entry is removed but the storage allocatedto the file is not made available until the original file is no longer in use.

    This function is semantically identical to unlink().

    3.3 新版功能: dir_fd 参数。

    在 3.6 版更改: 接受一个 类路径对象。

    • os.removedirs(name)
    • Remove directories recursively. Works like rmdir() except that, if theleaf directory is successfully removed, removedirs() tries tosuccessively remove every parent directory mentioned in path until an erroris raised (which is ignored, because it generally means that a parent directoryis not empty). For example, os.removedirs('foo/bar/baz') will first removethe directory 'foo/bar/baz', and then remove 'foo/bar' and 'foo' ifthey are empty. Raises OSError if the leaf directory could not besuccessfully removed.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
    • Rename the file or directory src to dst. If dst exists, the operationwill fail with an OSError subclass in a number of cases:

    On Windows, if dst exists a FileExistsError is always raised.

    On Unix, if src is a file and dst is a directory or vice-versa, anIsADirectoryError or a NotADirectoryError will be raisedrespectively. If both are directories and dst is empty, dst will besilently replaced. If dst is a non-empty directory, an OSErroris raised. If both are files, dst it will be replaced silently if the userhas permission. The operation may fail on some Unix flavors if src anddst are on different filesystems. If successful, the renaming will be anatomic operation (this is a POSIX requirement).

    This function can support specifying src_dir_fd and/or dst_dir_fd tosupply paths relative to directory descriptors.

    If you want cross-platform overwriting of the destination, use replace().

    3.3 新版功能: The src_dir_fd and dst_dir_fd arguments.

    在 3.6 版更改: Accepts a path-like object for src and dst.

    • os.renames(old, new)
    • Recursive directory or file renaming function. Works like rename(), exceptcreation of any intermediate directories needed to make the new pathname good isattempted first. After the rename, directories corresponding to rightmost pathsegments of the old name will be pruned away using removedirs().

    注解

    This function can fail with the new directory structure made if you lackpermissions needed to remove the leaf directory or file.

    在 3.6 版更改: Accepts a path-like object for old and new.

    • os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
    • Rename the file or directory src to dst. If dst is a directory,OSError will be raised. If dst exists and is a file, it willbe replaced silently if the user has permission. The operation may failif src and dst are on different filesystems. If successful,the renaming will be an atomic operation (this is a POSIX requirement).

    This function can support specifying src_dir_fd and/or dst_dir_fd tosupply paths relative to directory descriptors.

    3.3 新版功能.

    在 3.6 版更改: Accepts a path-like object for src and dst.

    • os.rmdir(path, *, dir_fd=None)
    • Remove (delete) the directory path. If the directory does not exist or isnot empty, an FileNotFoundError or an OSError is raisedrespectively. In order to remove whole directory trees,shutil.rmtree() can be used.

    This function can support paths relative to directory descriptors.

    3.3 新版功能: The dir_fd parameter.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.scandir(path='.')
    • Return an iterator of os.DirEntry objects corresponding to theentries in the directory given by path. The entries are yielded inarbitrary order, and the special entries '.' and '..' are notincluded.

    Using scandir() instead of listdir() can significantlyincrease the performance of code that also needs file type or fileattribute information, because os.DirEntry objects expose thisinformation if the operating system provides it when scanning a directory.All os.DirEntry methods may perform a system call, butis_dir() and is_file() usually onlyrequire a system call for symbolic links; os.DirEntry.stat()always requires a system call on Unix but only requires one forsymbolic links on Windows.

    path may be a path-like object. If path is of type bytes(directly or indirectly through the PathLike interface),the type of the name and pathattributes of each os.DirEntry will be bytes; in all othercircumstances, they will be of type str.

    This function can also support specifying a file descriptor; the file descriptor must refer to a directory.

    Raises an auditing event os.scandir with argument path.

    The scandir() iterator supports the context manager protocoland has the following method:

    • scandir.close()
    • Close the iterator and free acquired resources.

    This is called automatically when the iterator is exhausted or garbagecollected, or when an error happens during iterating. However itis advisable to call it explicitly or use the withstatement.

    3.6 新版功能.

    The following example shows a simple use of scandir() to display allthe files (excluding directories) in the given path that don't start with'.'. The entry.is_file() call will generally not make an additionalsystem call:

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

    注解

    On Unix-based systems, scandir() uses the system'sopendir()andreaddir()functions. On Windows, it uses the Win32FindFirstFileW.aspx)andFindNextFileW.aspx)functions.

    3.5 新版功能.

    3.6 新版功能: Added support for the context manager protocol and theclose() method. If a scandir() iterator is neitherexhausted nor explicitly closed a ResourceWarning will be emittedin its destructor.

    The function accepts a path-like object.

    在 3.7 版更改: Added support for file descriptors on Unix.

    • class os.DirEntry
    • Object yielded by scandir() to expose the file path and other fileattributes of a directory entry.

    scandir() will provide as much of this information as possible withoutmaking additional system calls. When a stat() or lstat() system callis made, the os.DirEntry object will cache the result.

    os.DirEntry instances are not intended to be stored in long-lived datastructures; if you know the file metadata has changed or if a long time haselapsed since calling scandir(), call os.stat(entry.path) to fetchup-to-date information.

    Because the os.DirEntry methods can make operating system calls, they mayalso raise OSError. If you need very fine-grainedcontrol over errors, you can catch OSError when calling one of theos.DirEntry methods and handle as appropriate.

    To be directly usable as a path-like object, os.DirEntryimplements the PathLike interface.

    Attributes and methods on a os.DirEntry instance are as follows:

    • name
    • The entry's base filename, relative to the scandir()_path_argument.

    The name attribute will be bytes if the scandir()path argument is of type bytes and str otherwise. Usefsdecode() to decode byte filenames.

    • path
    • The entry's full path name: equivalent to os.path.join(scandirpath,entry.name) where _scandir_path is the scandir()_path_argument. The path is only absolute if the scandir()_path_argument was absolute. If the scandir()_path_argument was a file descriptor, the pathattribute is the same as the name attribute.

    The path attribute will be bytes if the scandir()path argument is of type bytes and str otherwise. Usefsdecode() to decode byte filenames.

    • inode()
    • Return the inode number of the entry.

    The result is cached on the os.DirEntry object. Useos.stat(entry.path, follow_symlinks=False).st_ino to fetch up-to-dateinformation.

    On the first, uncached call, a system call is required on Windows butnot on Unix.

    • isdir(*, _follow_symlinks=True)
    • Return True if this entry is a directory or a symbolic link pointingto a directory; return False if the entry is or points to any otherkind of file, or if it doesn't exist anymore.

    If follow_symlinks is False, return True only if this entryis a directory (without following symlinks); return False if theentry is any other kind of file or if it doesn't exist anymore.

    The result is cached on the os.DirEntry object, with a separate cachefor follow_symlinks True and False. Call os.stat() alongwith stat.S_ISDIR() to fetch up-to-date information.

    On the first, uncached call, no system call is required in most cases.Specifically, for non-symlinks, neither Windows or Unix require a systemcall, except on certain Unix file systems, such as network file systems,that return dirent.dtype == DT_UNKNOWN. If the entry is a symlink,a system call will be required to follow the symlink unless_follow_symlinks is False.

    This method can raise OSError, such as PermissionError,but FileNotFoundError is caught and not raised.

    • isfile(*, _follow_symlinks=True)
    • Return True if this entry is a file or a symbolic link pointing to afile; return False if the entry is or points to a directory or othernon-file entry, or if it doesn't exist anymore.

    If follow_symlinks is False, return True only if this entryis a file (without following symlinks); return False if the entry isa directory or other non-file entry, or if it doesn't exist anymore.

    The result is cached on the os.DirEntry object. Caching, system callsmade, and exceptions raised are as per is_dir().

    • is_symlink()
    • Return True if this entry is a symbolic link (even if broken);return False if the entry points to a directory or any kind of file,or if it doesn't exist anymore.

    The result is cached on the os.DirEntry object. Callos.path.islink() to fetch up-to-date information.

    On the first, uncached call, no system call is required in most cases.Specifically, neither Windows or Unix require a system call, except oncertain Unix file systems, such as network file systems, that returndirent.d_type == DT_UNKNOWN.

    This method can raise OSError, such as PermissionError,but FileNotFoundError is caught and not raised.

    • stat(*, follow_symlinks=True)
    • Return a stat_result object for this entry. This methodfollows symbolic links by default; to stat a symbolic link add thefollow_symlinks=False argument.

    On Unix, this method always requires a system call. On Windows, itonly requires a system call if follow_symlinks is True and theentry is a reparse point (for example, a symbolic link or directoryjunction).

    On Windows, the st_ino, st_dev and st_nlink attributes of thestat_result are always set to zero. Call os.stat() toget these attributes.

    The result is cached on the os.DirEntry object, with a separate cachefor follow_symlinks True and False. Call os.stat() tofetch up-to-date information.

    Note that there is a nice correspondence between several attributesand methods of os.DirEntry and of pathlib.Path. Inparticular, the name attribute has the samemeaning, as do the is_dir(), is_file(), is_symlink()and stat() methods.

    3.5 新版功能.

    在 3.6 版更改: Added support for the PathLike interface. Added supportfor bytes paths on Windows.

    • os.stat(path, *, dir_fd=None, follow_symlinks=True)
    • Get the status of a file or a file descriptor. Perform the equivalent of astat() system call on the given path. path may be specified aseither a string or bytes — directly or indirectly through the PathLikeinterface — or as an open file descriptor. Return a stat_resultobject.

    This function normally follows symlinks; to stat a symlink add the argumentfollow_symlinks=False, or use lstat().

    This function can support specifying a file descriptor andnot following symlinks.

    On Windows, passing follow_symlinks=False will disable following allname-surrogate reparse points, which includes symlinks and directoryjunctions. Other types of reparse points that do not resemble links or thatthe operating system is unable to follow will be opened directly. Whenfollowing a chain of multiple links, this may result in the original linkbeing returned instead of the non-link that prevented full traversal. Toobtain stat results for the final path in this case, use theos.path.realpath() function to resolve the path name as far aspossible and call lstat() on the result. This does not apply todangling symlinks or junction points, which will raise the usual exceptions.

    示例:

    1. >>> import os
    2. >>> statinfo = os.stat('somefile.txt')
    3. >>> statinfo
    4. os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    5. st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    6. st_mtime=1297230027, st_ctime=1297230027)
    7. >>> statinfo.st_size
    8. 264

    参见

    fstat() and lstat() functions.

    3.3 新版功能: Added the dir_fd and follow_symlinks arguments, specifying a filedescriptor instead of a path.

    在 3.6 版更改: 接受一个 类路径对象。

    在 3.8 版更改: On Windows, all reparse points that can be resolved by the operatingsystem are now followed, and passing followsymlinks=Falsedisables following all name surrogate reparse points. If the operatingsystem reaches a reparse point that it is not able to follow, _stat nowreturns the information for the original path as iffollow_symlinks=False had been specified instead of raising an error.

    • class os.stat_result
    • Object whose attributes correspond roughly to the members of thestat structure. It is used for the result of os.stat(),os.fstat() and os.lstat().

    Attributes:

    • st_mode
    • File mode: file type and file mode bits (permissions).

    • st_ino

    • Platform dependent, but if non-zero, uniquely identifies thefile for a given value of st_dev. Typically:

      • the inode number on Unix,

      • the file index onWindows

    • st_dev

    • Identifier of the device on which this file resides.

    • st_nlink

    • Number of hard links.

    • st_uid

    • User identifier of the file owner.

    • st_gid

    • Group identifier of the file owner.

    • st_size

    • Size of the file in bytes, if it is a regular file or a symbolic link.The size of a symbolic link is the length of the pathname it contains,without a terminating null byte.

    Timestamps:

    • st_atime
    • Time of most recent access expressed in seconds.

    • st_mtime

    • Time of most recent content modification expressed in seconds.

    • st_ctime

    • Platform dependent:

      • the time of most recent metadata change on Unix,

      • the time of creation on Windows, expressed in seconds.

    • st_atime_ns

    • Time of most recent access expressed in nanoseconds as an integer.

    • st_mtime_ns

    • Time of most recent content modification expressed in nanoseconds as aninteger.

    • st_ctime_ns

    • Platform dependent:

      • the time of most recent metadata change on Unix,

      • the time of creation on Windows, expressed in nanoseconds as aninteger.

    注解

    The exact meaning and resolution of the st_atime,st_mtime, and st_ctime attributes depend on the operatingsystem and the file system. For example, on Windows systems using the FATor FAT32 file systems, st_mtime has 2-second resolution, andst_atime has only 1-day resolution. See your operating systemdocumentation for details.

    Similarly, although st_atime_ns, st_mtime_ns,and st_ctime_ns are always expressed in nanoseconds, manysystems do not provide nanosecond precision. On systems that doprovide nanosecond precision, the floating-point object used tostore st_atime, st_mtime, and st_ctimecannot preserve all of it, and as such will be slightly inexact.If you need the exact timestamps you should always usest_atime_ns, st_mtime_ns, and st_ctime_ns.

    On some Unix systems (such as Linux), the following attributes may also beavailable:

    • st_blocks
    • Number of 512-byte blocks allocated for file.This may be smaller than st_size/512 when the file has holes.

    • st_blksize

    • "Preferred" blocksize for efficient file system I/O. Writing to a file insmaller chunks may cause an inefficient read-modify-rewrite.

    • st_rdev

    • Type of device if an inode device.

    • st_flags

    • User defined flags for file.

    On other Unix systems (such as FreeBSD), the following attributes may beavailable (but may be only filled out if root tries to use them):

    • st_gen
    • File generation number.

    • st_birthtime

    • Time of file creation.

    On Solaris and derivatives, the following attributes may also beavailable:

    • st_fstype
    • String that uniquely identifies the type of the filesystem thatcontains the file.

    On Mac OS systems, the following attributes may also be available:

    • st_rsize
    • Real size of the file.

    • st_creator

    • Creator of the file.

    • st_type

    • File type.

    On Windows systems, the following attributes are also available:

    • st_file_attributes
    • Windows file attributes: dwFileAttributes member of theBYHANDLE_FILE_INFORMATION structure returned byGetFileInformationByHandle(). See the FILE_ATTRIBUTE*constants in the stat module.

    • st_reparse_tag

    • When st_file_attributes has the FILEATTRIBUTE_REPARSE_POINTset, this field contains the tag identifying the type of reparse point.See the IO_REPARSE_TAG* constants in the stat module.

    The standard module stat defines functions and constants that areuseful for extracting information from a stat structure. (OnWindows, some items are filled with dummy values.)

    For backward compatibility, a stat_result instance is alsoaccessible as a tuple of at least 10 integers giving the most important (andportable) members of the stat structure, in the orderst_mode, st_ino, st_dev, st_nlink,st_uid, st_gid, st_size, st_atime,st_mtime, st_ctime. More items may be added at the end bysome implementations. For compatibility with older Python versions,accessing stat_result as a tuple always returns integers.

    3.3 新版功能: Added the st_atime_ns, st_mtime_ns, andst_ctime_ns members.

    3.5 新版功能: Added the st_file_attributes member on Windows.

    在 3.5 版更改: Windows now returns the file index as st_ino whenavailable.

    3.7 新版功能: Added the st_fstype member to Solaris/derivatives.

    3.8 新版功能: Added the st_reparse_tag member on Windows.

    在 3.8 版更改: On Windows, the st_mode member now identifies specialfiles as S_IFCHR, S_IFIFO or S_IFBLKas appropriate.

    • os.statvfs(path)
    • Perform a statvfs() system call on the given path. The return value isan object whose attributes describe the filesystem on the given path, andcorrespond 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'sbit-flags: if ST_RDONLY is set, the filesystem is mountedread-only, and if ST_NOSUID is set, the semantics ofsetuid/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 (disallow program execution), ST_SYNCHRONOUS(writes are synced at once), ST_MANDLOCK (allow mandatory locks on an FS),ST_WRITE (write on file/directory/symlink), ST_APPEND(append-only file), ST_IMMUTABLE (immutable file), ST_NOATIME(do not update access times), ST_NODIRATIME (do not update directory accesstimes), ST_RELATIME (update atime relative to mtime/ctime).

    This function can support specifying a file descriptor.

    可用性: Unix。

    在 3.2 版更改: The ST_RDONLY and ST_NOSUID constants were added.

    3.3 新版功能: Added support for specifying path as an open file descriptor.

    在 3.4 版更改: The ST_NODEV, ST_NOEXEC, ST_SYNCHRONOUS,ST_MANDLOCK, ST_WRITE, ST_APPEND,ST_IMMUTABLE, ST_NOATIME, ST_NODIRATIME,and ST_RELATIME constants were added.

    在 3.6 版更改: 接受一个 类路径对象。

    3.7 新版功能: Added f_fsid.

    • os.supports_dir_fd
    • A set object indicating which functions in the osmodule accept an open file descriptor for their dir_fd parameter.Different platforms provide different features, and the underlyingfunctionality Python uses to implement the dir_fd parameter is notavailable on all platforms Python supports. For consistency's sake,functions that may support dir_fd always allow specifying theparameter, but will throw an exception if the functionality is usedwhen 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 descriptorfor its dir_fd parameter, use the in operator on supportsdir_fd.As an example, this expression evaluates to True if os.stat()accepts open file descriptors for _dir_fd on the local platform:

    1. os.stat in os.supports_dir_fd

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

    3.3 新版功能.

    • os.supports_effective_ids
    • A set object indicating whether os.access() permitsspecifying True for its effective_ids parameter on the local platform.(Specifying False for effective_ids is always supported on allplatforms.) If the local platform supports it, the collection will containos.access(); otherwise it will be empty.

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

    1. os.access in os.supports_effective_ids

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

    3.3 新版功能.

    • os.supports_fd
    • A set object indicating which functions in theos module permit specifying their path parameter as an open filedescriptor on the local platform. Different platforms provide differentfeatures, and the underlying functionality Python uses to accept open filedescriptors as path arguments is not available on all platforms Pythonsupports.

    To determine whether a particular function permits specifying an open filedescriptor for its path parameter, use the in operator onsupportsfd. As an example, this expression evaluates to True ifos.chdir() accepts open file descriptors for _path on your localplatform:

    1. os.chdir in os.supports_fd

    3.3 新版功能.

    • os.supports_follow_symlinks
    • A set object indicating which functions in the os moduleaccept False for their follow_symlinks parameter on the local platform.Different platforms provide different features, and the underlyingfunctionality Python uses to implement follow_symlinks is not availableon all platforms Python supports. For consistency's sake, functions thatmay support follow_symlinks always allow specifying the parameter, butwill throw an exception if the functionality is used when it's not locallyavailable. (Specifying True for follow_symlinks is always supportedon all platforms.)

    To check whether a particular function accepts False for itsfollow_symlinks parameter, use the in operator onsupports_follow_symlinks. As an example, this expression evaluatesto True if you may specify follow_symlinks=False when callingos.stat() on the local platform:

    1. os.stat in os.supports_follow_symlinks

    3.3 新版功能.

    • os.symlink(src, dst, target_is_directory=False, *, dir_fd=None)
    • Create a symbolic link pointing to src named dst.

    On Windows, a symlink represents either a file or a directory, and does notmorph to the target dynamically. If the target is present, the type of thesymlink will be created to match. Otherwise, the symlink will be createdas a directory if target_is_directory is True or a file symlink (thedefault) otherwise. On non-Windows platforms, target_is_directory is ignored.

    This function can support paths relative to directory descriptors.

    注解

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

    OSError is raised when the function is called by an unprivilegeduser.

    可用性: Unix, Windows。

    在 3.2 版更改: Added support for Windows 6.0 (Vista) symbolic links.

    3.3 新版功能: Added the dir_fd argument, and now allow _target_is_directory_on non-Windows platforms.

    在 3.6 版更改: Accepts a path-like object for src and dst.

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

    • os.sync()
    • Force write of everything to disk.

    可用性: Unix。

    3.3 新版功能.

    • os.truncate(path, length)
    • Truncate the file corresponding to path, so that it is at mostlength bytes in size.

    This function can support specifying a file descriptor.

    Raises an auditing event os.truncate with arguments path, length.

    可用性: Unix, Windows。

    3.3 新版功能.

    在 3.5 版更改: 添加了 Windows 支持

    在 3.6 版更改: 接受一个 类路径对象。

    • os.unlink(path, *, dir_fd=None)
    • Remove (delete) the file path. This function is semanticallyidentical to remove(); the unlink name is itstraditional Unix name. Please see the documentation forremove() for further information.

    3.3 新版功能: The dir_fd parameter.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.utime(path, times=None, *, [ns, ]dir_fd=None, follow_symlinks=True)
    • Set the access and modified times of the file specified by path.

    utime() takes two optional parameters, times and ns.These specify the times set on path and are used as follows:

    • If ns is specified,it must be a 2-tuple of the form (atime_ns, mtime_ns)where each member is an int expressing nanoseconds.

    • If times is not None,it must be a 2-tuple of the form (atime, mtime)where each member is an int or float expressing seconds.

    • If times is None and ns is unspecified,this is equivalent to specifying ns=(atime_ns, mtime_ns)where both times are the current time.

    It is an error to specify tuples for both times and ns.

    Note that the exact times you set here may not be returned by a subsequentstat() call, depending on the resolution with which your operatingsystem records access and modification times; see stat(). The bestway to preserve exact times is to use the st_atime_ns and st_mtime_ns_fields from the os.stat() result object with the _ns parameter toutime.

    This function can support specifying a file descriptor,paths relative to directory descriptors and notfollowing symlinks.

    3.3 新版功能: Added support for specifying path as an open file descriptor,and the dir_fd, follow_symlinks, and ns parameters.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.walk(top, topdown=True, onerror=None, followlinks=False)
    • Generate the file names in a directory tree by walking the treeeither top-down or bottom-up. For each directory in the tree rooted at directorytop (including top itself), it yields a 3-tuple (dirpath, dirnames,filenames).

    dirpath is a string, the path to the directory. dirnames is a list of thenames of the subdirectories in dirpath (excluding '.' and '..').filenames is a list of the names of the non-directory files in dirpath.Note that the names in the lists contain no path components. To get a full path(which begins with top) to a file or directory in dirpath, doos.path.join(dirpath, name).

    If optional argument topdown is True or not specified, the triple for adirectory is generated before the triples for any of its subdirectories(directories are generated top-down). If topdown is False, the triplefor a directory is generated after the triples for all of its subdirectories(directories are generated bottom-up). No matter the value of topdown, thelist of subdirectories is retrieved before the tuples for the directory andits subdirectories are generated.

    When topdown is True, the caller can modify the dirnames list in-place(perhaps using del or slice assignment), and walk() will onlyrecurse into the subdirectories whose names remain in dirnames; this can beused to prune the search, impose a specific order of visiting, or even to informwalk() about directories the caller creates or renames before it resumeswalk() again. Modifying dirnames when topdown is False hasno effect on the behavior of the walk, because in bottom-up mode the directoriesin dirnames are generated before dirpath itself is generated.

    By default, errors from the scandir() call are ignored. If optionalargument onerror is specified, it should be a function; it will be called withone argument, an OSError instance. It can report the error to continuewith the walk, or raise the exception to abort the walk. Note that the filenameis available as the filename attribute of the exception object.

    By default, walk() will not walk down into symbolic links that resolve todirectories. Set followlinks to True to visit directories pointed to bysymlinks, on systems that support them.

    注解

    Be aware that setting followlinks to True can lead to infiniterecursion 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 directorybetween resumptions of walk(). walk() never changes the currentdirectory, and assumes that its caller doesn't either.

    This example displays the number of bytes taken by non-directory files in eachdirectory under the starting directory, except that it doesn't look under anyCVS subdirectory:

    1. import os
    2. from os.path import join, getsize
    3. for root, dirs, files in os.walk('python/Lib/email'):
    4. print(root, "consumes", end=" ")
    5. print(sum(getsize(join(root, name)) for name in files), end=" ")
    6. print("bytes in", len(files), "non-directory files")
    7. if 'CVS' in dirs:
    8. 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 allowdeleting a directory before the directory is empty:

    1. # Delete everything reachable from the directory named in "top",
    2. # assuming there are no symbolic links.
    3. # CAUTION: This is dangerous! For example, if top == '/', it
    4. # could delete all your disk files.
    5. import os
    6. for root, dirs, files in os.walk(top, topdown=False):
    7. for name in files:
    8. os.remove(os.path.join(root, name))
    9. for name in dirs:
    10. os.rmdir(os.path.join(root, name))

    在 3.5 版更改: This function now calls os.scandir() instead of os.listdir(),making it faster by reducing the number of calls to os.stat().

    在 3.6 版更改: 接受一个 类路径对象。

    • os.fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)
    • This behaves exactly like walk(), except that it yields a 4-tuple(dirpath, dirnames, filenames, dirfd), and it supports 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 paths relative to directory descriptors and not following symlinks. Note howeverthat, unlike other functions, the fwalk() default value forfollow_symlinks is False.

    注解

    Since fwalk() yields file descriptors, those are only valid untilthe next iteration step, so you should duplicate them (e.g. withdup()) if you want to keep them longer.

    This example displays the number of bytes taken by non-directory files in eachdirectory under the starting directory, except that it doesn't look under anyCVS subdirectory:

    1. import os
    2. for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
    3. print(root, "consumes", end="")
    4. print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
    5. end="")
    6. print("bytes in", len(files), "non-directory files")
    7. if 'CVS' in dirs:
    8. 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 isempty:

    1. # Delete everything reachable from the directory named in "top",
    2. # assuming there are no symbolic links.
    3. # CAUTION: This is dangerous! For example, if top == '/', it
    4. # could delete all your disk files.
    5. import os
    6. for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
    7. for name in files:
    8. os.unlink(name, dir_fd=rootfd)
    9. for name in dirs:
    10. os.rmdir(name, dir_fd=rootfd)

    可用性: Unix。

    3.3 新版功能.

    在 3.6 版更改: 接受一个 类路径对象。

    在 3.7 版更改: Added support for bytes paths.

    • os.memfdcreate(_name[, flags=os.MFD_CLOEXEC])
    • Create an anonymous file and return a file descriptor that refers to it.flags must be one of the os.MFD_* constants available on the system(or a bitwise ORed combination of them). By default, the new filedescriptor is non-inheritable.

    The name supplied in name is used as a filename and will be displayed asthe 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 ofthe file descriptor, and as such multiple files can have the same namewithout any side effects.

    Availability: Linux 3.17 or newer with glibc 2.27 or newer.

    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
    • These flags can be passed to memfd_create().

    Availability: Linux 3.17 or newer with glibc 2.27 or newer. TheMFD_HUGE* flags are only available since Linux 4.14.

    3.8 新版功能.

    Linux extended attributes

    3.3 新版功能.

    These functions are all available on Linux only.

    • os.getxattr(path, attribute, *, follow_symlinks=True)
    • Return the value of the extended filesystem attribute attribute forpath. attribute can be bytes or str (directly or indirectly through thePathLike interface). If it is str, it is encoded with the filesystemencoding.

    This function can support specifying a file descriptor andnot following symlinks.

    在 3.6 版更改: Accepts a path-like object for path and attribute.

    • os.listxattr(path=None, *, follow_symlinks=True)
    • Return a list of the extended filesystem attributes on path. Theattributes in the list are represented as strings decoded with the filesystemencoding. If path is None, listxattr() will examine the currentdirectory.

    This function can support specifying a file descriptor andnot following symlinks.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.removexattr(path, attribute, *, follow_symlinks=True)
    • Removes the extended filesystem attribute attribute from path.attribute should be bytes or str (directly or indirectly through thePathLike interface). If it is a string, it is encodedwith the filesystem encoding.

    This function can support specifying a file descriptor andnot following symlinks.

    在 3.6 版更改: Accepts a path-like object for path and attribute.

    • os.setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)
    • Set the extended filesystem attribute attribute on path to value.attribute must be a bytes or str with no embedded NULs (directly orindirectly through the PathLike interface). If it is a str,it is encoded with the filesystem encoding. flags may beXATTR_REPLACE or XATTR_CREATE. If XATTR_REPLACE isgiven and the attribute does not exist, EEXISTS will be raised.If XATTR_CREATE is given and the attribute already exists, theattribute will not be created and ENODATA will be raised.

    This function can support specifying a file descriptor andnot following symlinks.

    注解

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

    在 3.6 版更改: Accepts a path-like object for path and attribute.

    • os.XATTR_SIZE_MAX
    • The maximum size the value of an extended attribute can be. Currently, thisis 64 KiB on Linux.

    • os.XATTR_CREATE

    • This is a possible value for the flags argument in setxattr(). Itindicates the operation must create an attribute.

    • os.XATTR_REPLACE

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

    Process Management

    These functions may be used to create and manage processes.

    The various exec* functions take a list of arguments for the newprogram loaded into the process. In each case, the first of these arguments ispassed to the new program as its own name rather than as an argument a user mayhave typed on a command line. For the C programmer, this is the argv[0]passed to a program's main(). For example, os.execv('/bin/echo',['foo', 'bar']) will only print bar on standard output; foo will seemto be ignored.

    • os.abort()
    • Generate a SIGABRT signal to the current process. On Unix, the defaultbehavior is to produce a core dump; on Windows, the process immediately returnsan exit code of 3. Be aware that calling this function will not call thePython signal handler registered for SIGABRT withsignal.signal().

    • os.adddll_directory(_path)

    • Add a path to the DLL search path.

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

    Remove the directory by calling close() on the returned objector using it in a with statement.

    See the Microsoft documentationfor more information about how DLLs are loaded.

    可用性: Windows。

    3.8 新版功能: Previous versions of CPython would resolve DLLs using the defaultbehavior for the current process. This led to inconsistencies,such as only sometimes searching PATH or the currentworking directory, and OS functions such as AddDllDirectoryhaving no effect.

    In 3.8, the two primary ways DLLs are loaded now explicitlyoverride the process-wide behavior to ensure consistency. See theporting notes for information onupdating libraries.

    • 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; theydo 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 asOSError exceptions.

    The current process is replaced immediately. Open file objects anddescriptors are not flushed, so if there may be data bufferedon these open files, you should flush them usingsys.stdout.flush() or os.fsync() before calling anexec* function.

    The "l" and "v" variants of the exec* functions differ in howcommand-line arguments are passed. The "l" variants are perhaps the easiestto work with if the number of parameters is fixed when the code is written; theindividual parameters simply become additional parameters to the execl*()functions. The "v" variants are good when the number of parameters isvariable, 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 withthe name of the command being run, but this is not enforced.

    The variants which include a "p" near the end (execlp(),execlpe(), execvp(), and execvpe()) will use thePATH environment variable to locate the program file. When theenvironment is being replaced (using one of the exec*e variants,discussed in the next paragraph), the new environment is used as the source ofthe PATH variable. The other variants, execl(), execle(),execv(), and execve(), will not use the PATH variable tolocate the executable; path must contain an appropriate absolute or relativepath.

    For execle(), execlpe(), execve(), and execvpe() (notethat these all end in "e"), the env parameter must be a mapping which isused to define the environment variables for the new process (these are usedinstead of the current process' environment); the functions execl(),execlp(), execv(), and execvp() all cause the new process toinherit the environment of the current process.

    For execve() on some platforms, path may also be specified as an openfile 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.

    可用性: Unix, Windows。

    3.3 新版功能: Added support for specifying path as an open file descriptorfor execve().

    在 3.6 版更改: 接受一个 类路径对象。

    • os.exit(_n)
    • Exit the process with status n, without calling cleanup handlers, flushingstdio buffers, etc.

    注解

    The standard way to exit is sys.exit(n). _exit() shouldnormally 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 programswritten 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 somevariation. These constants are defined where they are defined by the underlyingplatform.

    • os.EX_OK
    • Exit code that means no error occurred.

    可用性: Unix。

    • os.EX_USAGE
    • Exit code that means the command was used incorrectly, such as when the wrongnumber of arguments are given.

    可用性: Unix。

    • os.EX_DATAERR
    • Exit code that means the input data was incorrect.

    可用性: Unix。

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

    可用性: Unix。

    • os.EX_NOUSER
    • Exit code that means a specified user did not exist.

    可用性: Unix。

    • os.EX_NOHOST
    • Exit code that means a specified host did not exist.

    可用性: Unix。

    • os.EX_UNAVAILABLE
    • Exit code that means that a required service is unavailable.

    可用性: Unix。

    • os.EX_SOFTWARE
    • Exit code that means an internal software error was detected.

    可用性: Unix。

    • os.EX_OSERR
    • Exit code that means an operating system error was detected, such as theinability to fork or create a pipe.

    可用性: Unix。

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

    可用性: Unix。

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

    可用性: Unix。

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

    可用性: Unix。

    • os.EX_TEMPFAIL
    • Exit code that means a temporary failure occurred. This indicates somethingthat may not really be an error, such as a network connection that couldn't bemade during a retryable operation.

    可用性: Unix。

    • os.EX_PROTOCOL
    • Exit code that means that a protocol exchange was illegal, invalid, or notunderstood.

    可用性: Unix。

    • os.EX_NOPERM
    • Exit code that means that there were insufficient permissions to perform theoperation (but not intended for file system problems).

    可用性: Unix。

    • os.EX_CONFIG
    • Exit code that means that some kind of configuration error occurred.

    可用性: Unix。

    • os.EX_NOTFOUND
    • Exit code that means something like "an entry was not found".

    可用性: Unix。

    • os.fork()
    • Fork a child process. Return 0 in the child and the child's process id in theparent. If an error occurs OSError is raised.

    Note that some platforms including FreeBSD <= 6.3 and Cygwin haveknown issues when using fork() from a thread.

    在 3.8 版更改: Calling fork() in a subinterpreter is no longer supported(RuntimeError is raised).

    警告

    See ssl for applications that use the SSL module with fork().

    可用性: Unix。

    • os.forkpty()
    • Fork a child process, using a new pseudo-terminal as the child's controllingterminal. Return a pair of (pid, fd), where pid is 0 in the child, thenew child's process id in the parent, and fd is the file descriptor of themaster end of the pseudo-terminal. For a more portable approach, use thepty module. If an error occurs OSError is raised.

    在 3.8 版更改: Calling forkpty() in a subinterpreter is no longer supported(RuntimeError is raised).

    可用性: 某些 Unix。

    • os.kill(pid, sig)
    • Send signal sig to the process pid. Constants for the specific signalsavailable on the host platform are defined in the signal module.

    Windows: The signal.CTRL_C_EVENT andsignal.CTRL_BREAK_EVENT signals are special signals which canonly be sent to console processes which share a common console window,e.g., some subprocesses. Any other value for sig will cause the processto be unconditionally killed by the TerminateProcess API, and the exit codewill be set to sig. The Windows version of kill() additionally takesprocess handles to be killed.

    See also signal.pthread_kill().

    3.2 新版功能: Windows support.

    • os.killpg(pgid, sig)
    • Send the signal sig to the process group pgid.

    可用性: Unix。

    • os.nice(increment)
    • Add increment to the process's "niceness". Return the new niceness.

    可用性: Unix。

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

    可用性: Unix。

    • os.popen(cmd, mode='r', buffering=-1)
    • Open a pipe to or from command cmd.The return value is an open file objectconnected to the pipe, which can be read or written depending on whether mode_is 'r' (default) or 'w'. The _buffering argument has the same meaning asthe corresponding argument to the built-in open() function. Thereturned file object reads or writes text strings rather than bytes.

    The close method returns None if the subprocess exitedsuccessfully, or the subprocess's return code if there was anerror. On POSIX systems, if the return code is positive itrepresents the return value of the process left-shifted by onebyte. If the return code is negative, the process was terminatedby the signal given by the negated value of the return code. (Forexample, the return value might be - signal.SIGKILL if thesubprocess was killed.) On Windows systems, the return valuecontains the signed integer return code from the child process.

    This is implemented using subprocess.Popen; see that class'sdocumentation for more powerful ways to manage and communicate withsubprocesses.

    • os.posixspawn(_path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)
    • Wraps the posix_spawn() C library API for use from Python.

    Most users should use subprocess.run() instead of posix_spawn().

    The positional-only arguments path, args, and env are similar toexecve().

    The path parameter is the path to the executable file.The path shouldcontain a directory.Use posix_spawnp() to pass an executable filewithout directory.

    The file_actions argument may be a sequence of tuples describing actionsto take on specific file descriptors in the child process between the Clibrary implementation's fork() and exec() steps.The first item in each tuple must be one of the three type indicatorlisted below describing the remaining tuple elements:

    • os.POSIX_SPAWN_OPEN
    • (os.POSIXSPAWN_OPEN, _fd, path, flags, mode)

    Performs os.dup2(os.open(path, flags, mode), fd).

    • os.POSIX_SPAWN_CLOSE
    • (os.POSIXSPAWN_CLOSE, _fd)

    Performs os.close(fd).

    • os.POSIX_SPAWN_DUP2
    • (os.POSIXSPAWN_DUP2, _fd, new_fd)

    Performs os.dup2(fd, new_fd).

    These tuples correspond to the C libraryposix_spawn_file_actions_addopen(),posix_spawn_file_actions_addclose(), andposix_spawn_file_actions_adddup2() API calls used to preparefor the posix_spawn() call itself.

    The setpgroup argument will set the process group of the child to the valuespecified. If the value specified is 0, the child's process group ID will bemade the same as its process ID. If the value of setpgroup is not set, thechild will inherit the parent's process group ID. This argument correspondsto the C library POSIX_SPAWN_SETPGROUP flag.

    If the resetids argument is True it will reset the effective UID andGID of the child to the real UID and GID of the parent process. If theargument is False, then the child retains the effective UID and GID ofthe parent. In either case, if the set-user-ID and set-group-ID permissionbits are enabled on the executable file, their effect will override thesetting of the effective UID and GID. This argument corresponds to the Clibrary POSIX_SPAWN_RESETIDS flag.

    If the setsid argument is True, it will create a new session IDfor posix_spawn. setsid requires POSIX_SPAWN_SETSIDor POSIX_SPAWN_SETSID_NP flag. Otherwise, NotImplementedErroris raised.

    The setsigmask argument will set the signal mask to the signal setspecified. If the parameter is not used, then the child inherits theparent's signal mask. This argument corresponds to the C libraryPOSIX_SPAWN_SETSIGMASK flag.

    The sigdef argument will reset the disposition of all signals in the setspecified. This argument corresponds to the C libraryPOSIX_SPAWN_SETSIGDEF flag.

    The scheduler argument must be a tuple containing the (optional) schedulerpolicy and an instance of sched_param with the scheduler parameters.A value of None in the place of the scheduler policy indicates that isnot being provided. This argument is a combination of the C libraryPOSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDULERflags.

    3.8 新版功能.

    可用性: Unix。

    • os.posixspawnp(_path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)
    • Wraps the posix_spawnp() C library API for use from Python.

    Similar to posix_spawn() except that the system searchesfor the executable file in the list of directories specified by thePATH environment variable (in the same way as for execvp(3)).

    3.8 新版功能.

    Availability: See posix_spawn() documentation.

    • os.registerat_fork(*, _before=None, after_in_parent=None, after_in_child=None)
    • Register callables to be executed when a new child process is forkedusing 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 processafter 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 thePython interpreter. A typical subprocess launch will nottrigger them as the child is not going to re-enter the interpreter.

    Functions registered for execution before forking are called inreverse registration order. Functions registered for executionafter forking (either in the parent or in the child) are calledin registration order.

    Note that fork() calls made by third-party C code may notcall those functions, unless it explicitly calls PyOS_BeforeFork(),PyOS_AfterFork_Parent() and PyOS_AfterFork_Child().

    There is no way to unregister a function.

    可用性: Unix。

    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)
    • Execute the program path in a new process.

    (Note that the subprocess module provides more powerful facilities forspawning new processes and retrieving their results; using that module ispreferable to using these functions. Check especially theReplacing Older Functions with the subprocess Module section.)

    If mode is P_NOWAIT, this function returns the process id of the newprocess; if mode is P_WAIT, returns the process's exit code if itexits normally, or -signal, where signal is the signal that killed theprocess. On Windows, the process id will actually be the process handle, so canbe used with the waitpid() function.

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

    The "l" and "v" variants of the spawn* functions differ in howcommand-line arguments are passed. The "l" variants are perhaps the easiestto work with if the number of parameters is fixed when the code is written; theindividual parameters simply become additional parameters to thespawnl*() functions. The "v" variants are good when the number ofparameters is variable, with the arguments being passed in a list or tuple asthe args parameter. In either case, the arguments to the child process muststart with the name of the command being run.

    The variants which include a second "p" near the end (spawnlp(),spawnlpe(), spawnvp(), and spawnvpe()) will use thePATH environment variable to locate the program file. When theenvironment is being replaced (using one of the spawn*e variants,discussed in the next paragraph), the new environment is used as the source ofthe PATH variable. The other variants, spawnl(),spawnle(), spawnv(), and spawnve(), will not use thePATH variable to locate the executable; path must contain anappropriate absolute or relative path.

    For spawnle(), spawnlpe(), spawnve(), and spawnvpe()(note that these all end in "e"), the env parameter must be a mappingwhich is used to define the environment variables for the new process (they areused instead of the current process' environment); the functionsspawnl(), spawnlp(), spawnv(), and spawnvp() all causethe new process to inherit the environment of the current process. Note thatkeys and values in the env dictionary must be strings; invalid keys orvalues will cause the function to fail, with a return value of 127.

    As an example, the following calls to spawnlp() and spawnvpe() areequivalent:

    1. import os
    2. os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
    3.  
    4. L = ['cp', 'index.html', '/dev/null']
    5. os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)

    Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp()and spawnvpe() are not available on Windows. spawnle() andspawnve() are not thread-safe on Windows; we advise you to use thesubprocess module instead.

    在 3.6 版更改: 接受一个 类路径对象。

    • os.P_NOWAIT
    • os.P_NOWAITO
    • Possible values for the mode parameter to the spawn* family offunctions. If either of these values is given, the spawn*() functionswill return as soon as the new process has been created, with the process id asthe return value.

    可用性: Unix, Windows。

    • os.P_WAIT
    • Possible value for the mode parameter to the spawn* family offunctions. If this is given as mode, the spawn*() functions will notreturn until the new process has run to completion and will return the exit codeof the process the run is successful, or -signal if a signal kills theprocess.

    可用性: Unix, Windows。

    • os.P_DETACH
    • os.P_OVERLAY
    • Possible values for the mode parameter to the spawn* family offunctions. These are less portable than those listed above. P_DETACHis similar to P_NOWAIT, but the new process is detached from theconsole of the calling process. If P_OVERLAY is used, the currentprocess will be replaced; the spawn* function will not return.

    可用性: Windows。

    • os.startfile(path[, operation])
    • Start a file with its associated application.

    When operation is not specified or 'open', this acts like double-clickingthe file in Windows Explorer, or giving the file name as an argument to thestart command from the interactive command shell: the file is openedwith whatever application (if any) its extension is associated.

    When another operation is given, it must be a "command verb" that specifieswhat should be done with the file. Common verbs documented by Microsoft are'print' and 'edit' (to be used on files) as well as 'explore' and'find' (to be used on directories).

    startfile() returns as soon as the associated application is launched.There is no option to wait for the application to close, and no way to retrievethe application's exit status. The path parameter is relative to the currentdirectory. If you want to use an absolute path, make sure the first characteris not a slash ('/'); the underlying Win32 ShellExecute() functiondoesn't work if it is. Use the os.path.normpath() function to ensure thatthe path is properly encoded for Win32.

    To reduce interpreter startup overhead, the Win32 ShellExecute()function is not resolved until this function is first called. If the functioncannot be resolved, NotImplementedError will be raised.

    可用性: Windows。

    • os.system(command)
    • Execute the command (a string) in a subshell. This is implemented by callingthe Standard C function system(), and has the same limitations.Changes to sys.stdin, etc. are not reflected in the environment ofthe executed command. If command generates any output, it will be sent tothe interpreter standard output stream.

    On Unix, the return value is the exit status of the process encoded in theformat specified for wait(). Note that POSIX does not specify themeaning of the return value of the C system() function, so the returnvalue of the Python function is system-dependent.

    On Windows, the return value is that returned by the system shell afterrunning command. The shell is given by the Windows environment variableCOMSPEC: it is usually cmd.exe, which returns the exitstatus of the command run; on systems using a non-native shell, consult yourshell documentation.

    The subprocess module provides more powerful facilities for spawningnew processes and retrieving their results; using that module is preferableto using this function. See the Replacing Older Functions with the subprocess Module section inthe subprocess documentation for some helpful recipes.

    Raises an auditing event os.system with argument command.

    可用性: Unix, Windows。

    • os.times()
    • Returns the current global process times.The return value is an object with five attributes:

      • user - user time

      • system - system time

      • children_user - user time of all child processes

      • children_system - system time of all child processes

      • elapsed - elapsed real time since a fixed point in the past

    For backwards compatibility, this object also behaves like a five-tuplecontaining user, system, children_user,children_system, and elapsed in that order.

    See the Unix manual pagetimes(2)) and times(3)) manual page on Unix or the GetProcessTimes MSDN_ on Windows.On Windows, only user and system are known; the otherattributes are zero.

    可用性: Unix, Windows。

    在 3.3 版更改: 返回结果的类型由元组变成一个类似元组的对象,同时具有命名的属性。

    • os.wait()
    • Wait for completion of a child process, and return a tuple containing its pidand exit status indication: a 16-bit number, whose low byte is the signal numberthat killed the process, and whose high byte is the exit status (if the signalnumber is zero); the high bit of the low byte is set if a core file wasproduced.

    可用性: Unix。

    • os.waitid(idtype, id, options)
    • Wait for the completion of one or more child processes.idtype can be P_PID, P_PGID or P_ALL.id specifies the pid to wait on.options is constructed from the ORing of one or more of WEXITED,WSTOPPED or WCONTINUED and additionally may be ORed withWNOHANG or WNOWAIT. The return value is an objectrepresenting the data contained in the siginfo_t structure, namely:si_pid, si_uid, si_signo, si_status,si_code or None if WNOHANG is specified and there are nochildren in a waitable state.

    可用性: Unix。

    3.3 新版功能.

    • os.P_PID
    • os.P_PGID
    • os.P_ALL
    • These are the possible values for idtype in waitid(). They affecthow id is interpreted.

    可用性: Unix。

    3.3 新版功能.

    • os.WEXITED
    • os.WSTOPPED
    • os.WNOWAIT
    • Flags that can be used in options in waitid() that specify whatchild signal to wait for.

    可用性: Unix。

    3.3 新版功能.

    • os.CLD_EXITED
    • os.CLD_DUMPED
    • os.CLD_TRAPPED
    • os.CLD_CONTINUED
    • These are the possible values for si_code in the result returned bywaitid().

    可用性: Unix。

    3.3 新版功能.

    • os.waitpid(pid, options)
    • The details of this function differ on Unix and Windows.

    On Unix: Wait for completion of a child process given by process id pid, andreturn a tuple containing its process id and exit status indication (encoded asfor wait()). The semantics of the call are affected by the value of theinteger options, which should be 0 for normal operation.

    If pid is greater than 0, waitpid() requests status information forthat specific process. If pid is 0, the request is for the status of anychild in the process group of the current process. If pid is -1, therequest pertains to any child of the current process. If pid is less than-1, status is requested for any process in the process group -pid (theabsolute value of pid).

    An OSError is raised with the value of errno when the syscallreturns -1.

    On Windows: Wait for completion of a process given by process handle pid, andreturn 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 orequal to 0 has no special meaning on Windows, and raises an exception. Thevalue of integer options has no effect. pid can refer to any process whoseid is known, not necessarily a child process. The spawn*functions called with P_NOWAIT return suitable process handles.

    在 3.5 版更改: 如果系统调用被中断,但信号处理程序没有触发异常,此函数现在会重试系统调用,而不是触发 InterruptedError 异常 (原因详见 PEP 475)。

    • os.wait3(options)
    • Similar to waitpid(), except no process id argument is given and a3-element tuple containing the child's process id, exit status indication,and resource usage information is returned. Refer toresource.getrusage() for details on resource usageinformation. The option argument is the same as that provided towaitpid() and wait4().

    可用性: Unix。

    • os.wait4(pid, options)
    • Similar to waitpid(), except a 3-element tuple, containing the child'sprocess id, exit status indication, and resource usage information is returned.Refer to resource.getrusage() for details onresource usage information. The arguments to wait4() are the sameas those provided to waitpid().

    可用性: Unix。

    • os.WNOHANG
    • The option for waitpid() to return immediately if no child process statusis available immediately. The function returns (0, 0) in this case.

    可用性: Unix。

    • os.WCONTINUED
    • This option causes child processes to be reported if they have been continuedfrom a job control stop since their status was last reported.

    可用性: 部分 Unix 系统。

    • os.WUNTRACED
    • This option causes child processes to be reported if they have been stopped buttheir current state has not been reported since they were stopped.

    可用性: Unix。

    The following functions take a process status code as returned bysystem(), wait(), or waitpid() as a parameter. They may beused to determine the disposition of a process.

    • os.WCOREDUMP(status)
    • Return True if a core dump was generated for the process, otherwisereturn False.

    可用性: Unix。

    • os.WIFCONTINUED(status)
    • Return True if the process has been continued from a job control stop,otherwise return False.

    可用性: Unix。

    • os.WIFSTOPPED(status)
    • Return True if the process has been stopped, otherwise returnFalse.

    可用性: Unix。

    • os.WIFSIGNALED(status)
    • Return True if the process exited due to a signal, otherwise returnFalse.

    可用性: Unix。

    • os.WIFEXITED(status)
    • Return True if the process exited using the exit(2)) system call,otherwise return False.

    可用性: Unix。

    • os.WEXITSTATUS(status)
    • 如果 WIFEXITED(status) 为值,则将整数形参返回给 exit(2)) 系统调用。 否则,返回值将没有任何意义。

    可用性: Unix。

    • os.WSTOPSIG(status)
    • 返回导致进程停止的信号。

    可用性: Unix。

    • os.WTERMSIG(status)
    • 返回导致进程退出的信号。

    可用性: Unix。

    调度器接口

    这些函数控制操作系统如何为进程分配 CPU 时间。 它们仅在某些 Unix 平台上可用。 更多细节信息请查阅你所用 Unix 的指南页面。

    3.3 新版功能.

    以下调度策略如果被操作系统支持就会对外公开。

    • os.SCHED_OTHER
    • 默认调度策略。

    • os.SCHED_BATCH

    • 用于 CPU 密集型进程的调度策略,它会尽量为计算机中的其余任务保留交互性。

    • os.SCHED_IDLE

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

    • os.SCHED_SPORADIC

    • 用于偶发型服务程序的调度策略。

    • os.SCHED_FIFO

    • 先进先出的调度策略。

    • os.SCHED_RR

    • 循环式的调度策略。

    • os.SCHED_RESET_ON_FORK

    • 此旗标可与任何其他调度策略进行 OR 运算。 当带有此旗标的进程设置分叉时,其子进程的调度策略和优先级会被重置为默认值。

    • class os.schedparam(_sched_priority)

    • 这个类表示在 sched_setparam(), sched_setscheduler()sched_getparam() 中使用的可修改调度形参。 它属于不可变对象。

    目前它只有一个可能的形参:

    • sched_priority
    • 一个调度策略的调度优先级。
    • os.schedget_priority_min(_policy)
    • 获取 policy 的最小优先级数值。 policy 是以上调度策略常量之一。

    • os.schedget_priority_max(_policy)

    • 获取 policy 的最高优先级数值。 policy 是以上调度策略常量之一。

    • os.schedsetscheduler(_pid, policy, param)

    • Set the scheduling policy for the process with PID pid. A pid of 0 meansthe calling process. policy is one of the scheduling policy constantsabove. param is a sched_param instance.

    • os.schedgetscheduler(_pid)

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

    • os.schedsetparam(_pid, param)

    • Set a scheduling parameters for the process with PID pid. A pid of 0 meansthe calling process. param is a sched_param instance.

    • os.schedgetparam(_pid)

    • Return the scheduling parameters as a sched_param instance for theprocess with PID pid. A pid of 0 means the calling process.

    • os.schedrr_get_interval(_pid)

    • Return the round-robin quantum in seconds for the process with PID pid. Apid of 0 means the calling process.

    • os.sched_yield()

    • Voluntarily relinquish the CPU.

    • os.schedsetaffinity(_pid, mask)

    • Restrict the process with PID pid (or the current process if zero) to aset of CPUs. mask is an iterable of integers representing the set ofCPUs to which the process should be restricted.

    • os.schedgetaffinity(_pid)

    • Return the set of CPUs the process with PID pid (or the current processif zero) is restricted to.

    Miscellaneous System Information

    • os.confstr(name)
    • Return string-valued system configuration values. name specifies theconfiguration value to retrieve; it may be a string which is the name of adefined 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 theconfstrnames dictionary. For configuration variables not included in thatmapping, passing an integer for _name is also accepted.

    If the configuration value specified by name isn't defined, None isreturned.

    If name is a string and is not known, ValueError is raised. If aspecific value for name is not supported by the host system, even if it isincluded in confstr_names, an OSError is raised witherrno.EINVAL for the error number.

    可用性: Unix。

    • os.confstr_names
    • Dictionary mapping names accepted by confstr() to the integer valuesdefined for those names by the host operating system. This can be used todetermine the set of names known to the system.

    可用性: Unix。

    • os.cpu_count()
    • Return the number of CPUs in the system. Returns None if undetermined.

    该数量不同于当前进程可以使用的CPU数量。可用的CPU数量可以由 len(os.sched_getaffinity(0)) 方法获得。

    3.4 新版功能.

    • os.getloadavg()
    • Return the number of processes in the system run queue averaged over the last1, 5, and 15 minutes or raises OSError if the load average wasunobtainable.

    可用性: Unix。

    • os.sysconf(name)
    • Return integer-valued system configuration values. If the configuration valuespecified by name isn't defined, -1 is returned. The comments regardingthe name parameter for confstr() apply here as well; the dictionary thatprovides information on the known names is given by sysconf_names.

    可用性: Unix。

    • os.sysconf_names
    • Dictionary mapping names accepted by sysconf() to the integer valuesdefined for those names by the host operating system. This can be used todetermine the set of names known to the system.

    可用性: Unix。

    The following data values are used to support path manipulation operations. Theseare defined for all platforms.

    Higher-level operations on pathnames are defined in the os.path module.

    • os.curdir
    • The constant string used by the operating system to refer to the currentdirectory. This is '.' for Windows and POSIX. Also available viaos.path.

    • os.pardir

    • The constant string used by the operating system to refer to the parentdirectory. This is '..' for Windows and POSIX. Also available viaos.path.

    • os.sep

    • The character used by the operating system to separate pathname components.This is '/' for POSIX and '\' for Windows. Note that knowing thisis not sufficient to be able to parse or concatenate pathnames —- useos.path.split() and os.path.join() —- but it is occasionallyuseful. Also available via os.path.

    • os.altsep

    • An alternative character used by the operating system to separate pathnamecomponents, or None if only one separator character exists. This is set to'/' on Windows systems where sep is a backslash. Also available viaos.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 searchpath components (as in PATH), such as ':' for POSIX or ';' forWindows. Also available via os.path.

    • os.defpath

    • The default search path used by execp andspawnp 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 currentplatform. This may be a single character, such as '\n' for POSIX, ormultiple characters, for example, '\r\n' for Windows. Do not useos.linesep as a line terminator when writing files opened in text mode (thedefault); use a single '\n' instead, on all platforms.

    • os.devnull

    • The file path of the null device. For example: '/dev/null' forPOSIX, 'nul' for Windows. Also available via os.path.

    • os.RTLD_LAZY

    • os.RTLD_NOW
    • os.RTLD_GLOBAL
    • os.RTLD_LOCAL
    • os.RTLD_NODELETE
    • os.RTLD_NOLOAD
    • os.RTLD_DEEPBIND
    • Flags for use with the setdlopenflags() andgetdlopenflags() functions. See the Unix manual pagedlopen(3)) for what the different flags mean.

    3.3 新版功能.

    Random numbers

    • os.getrandom(size, flags=0)
    • Get up to size random bytes. The function can return less bytes thanrequested.

    These bytes can be used to seed user-space random number generators or forcryptographic purposes.

    getrandom() relies on entropy gathered from device drivers and othersources of environmental noise. Unnecessarily reading large quantities ofdata will have a negative impact on other users of the /dev/random and/dev/urandom devices.

    The flags argument is a bit mask that can contain zero or more of thefollowing values ORed together: os.GRND_RANDOM andGRND_NONBLOCK.

    See also the Linux getrandom() manual page.

    Availability: Linux 3.17 and newer.

    3.6 新版功能.

    • os.urandom(size)
    • Return a string of size random bytes suitable for cryptographic use.

    This function returns random bytes from an OS-specific randomness source. Thereturned data should be unpredictable enough for cryptographic applications,though its exact quality depends on the OS implementation.

    On Linux, if the getrandom() syscall is available, it is used inblocking mode: block until the system urandom entropy pool is initialized(128 bits of entropy are collected by the kernel). See the PEP 524 forthe rationale. On Linux, the getrandom() function can be used to getrandom bytes in non-blocking mode (using the GRND_NONBLOCK flag) orto poll until the system urandom entropy pool is initialized.

    On a Unix-like system, random bytes are read from the /dev/urandomdevice. If the /dev/urandom device is not available or not readable, theNotImplementedError exception is raised.

    On Windows, it will use CryptGenRandom().

    参见

    The secrets module provides higher level functions. For aneasy-to-use interface to the random number generator provided by yourplatform, please see random.SystemRandom.

    在 3.6.0 版更改: On Linux, getrandom() is now used in blocking mode to increase thesecurity.

    在 3.5.2 版更改: On Linux, if the getrandom() syscall blocks (the urandom entropy poolis not initialized yet), fall back on reading /dev/urandom.

    在 3.5 版更改: On Linux 3.17 and newer, the getrandom() syscall is now usedwhen available. On OpenBSD 5.6 and newer, the C getentropy()function is now used. These functions avoid the usage of an internal filedescriptor.

    • os.GRND_NONBLOCK
    • By default, when reading from /dev/random, getrandom() blocks ifno random bytes are available, and when reading from /dev/urandom, it blocksif the entropy pool has not yet been initialized.

    If the GRND_NONBLOCK flag is set, then getrandom() does notblock in these cases, but instead immediately raises BlockingIOError.

    3.6 新版功能.

    • os.GRND_RANDOM
    • If this bit is set, then random bytes are drawn from the/dev/random pool instead of the /dev/urandom pool.

    3.6 新版功能.