16.1. os — 杂项操作系统接口

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

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

  • The design of all built-in operating system dependent modules of Python is such that as long as the same functionality is available, it uses the same interface; for example, the function os.stat(path) returns stat information about path in the same format (which happens to have originated with the POSIX interface).
  • Extensions peculiar to a particular operating system are also available 透过 os module, but using them is of course a threat to portability.
  • All functions accepting path or file names accept both bytes and string objects, and result in an object of the same type, if a path or file name is 被返回。
  • An “Availability: Unix” note means that this function is commonly found on Unix systems. It does not make any claims about its existence on a specific operating system.
  • If not separately noted, all functions that claim “Availability: Unix” are supported on Mac OS X, which builds on a Unix core.

注意

此模块中的所有函数会引发 OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

exception os. error

别名为内置 OSError 异常。

os. 名称

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

另请参阅

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

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

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

In Python, file names, command line arguments, and environment variables are represented using the string type. On some systems, decoding these strings to and from bytes is necessary before passing them to the operating system. Python uses the file system encoding to perform this conversion (see sys.getfilesystemencoding() ).

3.1 版改变: 在某些系统,使用文件系统编码转换可能失败。在这种情况下,Python 使用 surrogateescape encoding error handler, which means that undecodable bytes are replaced by a Unicode character U+DCxx on decoding, and these are again translated to the original byte on encoding.

The file system encoding must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions may raise UnicodeErrors.

16.1.2. 进程参数

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

os. ctermid ( )

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

可用性:Unix。

os. environ

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

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

若平台支持 putenv() 函数,此映射可用于修改环境及查询环境。 putenv() 将被自动调用当映射被修改时。

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

注意

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

注意

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

putenv() is not provided, a modified copy of this mapping may be passed to the appropriate process-creation functions to cause child processes to use a modified environment.

若平台支持 unsetenv() function, you can delete items in this mapping to unset environment variables. unsetenv() 会被自动调用当删除项从 os.environ ,和当某一 pop() or clear() 方法被调用。

os. environb

字节版本的 environ 映射 对象以字节字符串形式表示环境。 environ and environb 是同步的 (修改 environb 更新 environ ,反之亦然)。

environb 才可用,若 supports_bytes_environ 为 True。

3.2 版新增。

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

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

os. fsencode ( filename )

编码 filename 成文件系统编码采用 'surrogateescape' 错误处理程序,或 'strict' 在 Windows;返回 bytes 不变。

fsdecode() 是反函数。

3.2 版新增。

os. fsdecode ( filename )

解码 filename 从文件系统编码采用 'surrogateescape' 错误处理程序,或 'strict' 在 Windows;返回 str 不变。

fsencode() 是反函数。

3.2 版新增。

os. getenv ( key , default=None )

返回值对于环境变量 key 若存在,或 default 若它没有。 key , default 且结果是 str。

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

可用性:大多数风味的 Unix、Windows。

os. getenvb ( key , default=None )

返回值对于环境变量 key 若存在,或 default 若它没有。 key , default 且结果是 bytes。

可用性:大多数风味的 Unix。

3.2 版新增。

os. get_exec_path ( env=None )

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

3.2 版新增。

os. getegid ( )

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

可用性:Unix。

os. geteuid ( )

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

可用性:Unix。

os. getgid ( )

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

可用性:Unix。

os. getgrouplist ( user , group )

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

可用性:Unix。

3.3 版新增。

os. getgroups ( )

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

可用性:Unix。

注意

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

os. getlogin ( )

Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use the environment variables LOGNAME or USERNAME to find out who the user is, or pwd.getpwuid(os.getuid())[0] 以获取当前真实用户 ID 的登录名。

可用性:Unix Windows。

os. getpgid ( pid )

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

可用性:Unix。

os. getpgrp ( )

返回当前进程组的 ID。

可用性:Unix。

os. getpid ( )

返回当前进程 ID。

可用性:Unix Windows。

os. getppid ( )

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

可用性:Unix Windows。

3.2 版改变: 添加支持 Windows。

os. getpriority ( which , who )

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

可用性:Unix。

3.3 版新增。

os. PRIO_PROCESS
os. PRIO_PGRP
os. PRIO_USER

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

可用性:Unix。

3.3 版新增。

os. getresuid ( )

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

可用性:Unix。

3.2 版新增。

os. getresgid ( )

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

可用性:Unix。

3.2 版新增。

os. getuid ( )

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

可用性:Unix。

os. initgroups ( username , gid )

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

可用性:Unix。

3.2 版新增。

os. putenv ( key , value )

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

可用性:大多数风味的 Unix、Windows。

注意

在某些平台,括 FreeBSD 和 Mac OS X,设置 environ may cause memory leaks. Refer to the system documentation for putenv.

putenv() is supported, assignments to items in os.environ 会被自动翻译成相应调用 putenv() ;不管怎样,调用 putenv() 不更新 os.environ , so it is actually preferable to assign to items of os.environ .

os. setegid ( egid )

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

可用性:Unix。

os. seteuid ( euid )

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

可用性:Unix。

os. setgid ( gid )

设置当前进程的组 ID。

可用性:Unix。

os. setgroups ( groups )

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

可用性:Unix。

注意

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

os. setpgrp ( )

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

可用性:Unix。

os. setpgid ( pid , pgrp )

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

可用性:Unix。

os. setpriority ( which , who , priority )

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

可用性:Unix

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

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

可用性:Unix。

os. setuid ( uid )

设置当前进程的用户 ID。

可用性:Unix。

os. strerror ( code )

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

可用性:Unix Windows。

os. supports_bytes_environ

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

3.2 版新增。

os. umask ( mask )

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

可用性:Unix Windows。

os. uname ( )

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

  • sysname - 操作系统名称
  • nodename - 网络中的机器名称 (实现定义)
  • release - 操作系统发行
  • version - 操作系统版本
  • machine - 硬件标识符

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

某些系统截取 nodename 至 8 个字符或至前导分量;获取主机名的更优办法是 socket.gethostname() 或者甚至 socket.gethostbyaddr(socket.gethostname()) .

可用性:最近风味的 Unix。

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

os. unsetenv ( key )

取消设置 (删除) 环境变量命名 key 。对环境的这种改变会影响子进程的启动采用 os.system() , popen() or fork() and execv() .

unsetenv() is supported, deletion of items in os.environ is automatically translated into a corresponding call to unsetenv() ;不管怎样,调用 unsetenv() 不更新 os.environ , so it is actually preferable to delete items of os.environ .

可用性:大多数风味的 Unix、Windows。

16.1.3. 文件对象创建

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

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

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

16.1.4. 文件描述符操作

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

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

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

os. close ( fd )

关闭文件描述符 fd .

可用性:Unix Windows。

注意

此函数旨在低级 I/O 且必须应用于文件描述符如返回通过 os.open() or pipe() 。要关闭 "文件对象" 返回通过内置函数 open() 或通过 popen() or fdopen() ,使用其 close() 方法。

os. closerange ( fd_low , fd_high )

关闭所有文件描述符从 fd_low (包括在内) 到 fd_high (排除),忽略错误。相当于 (但更快相比):

for fd in range(fd_low, fd_high):
    try:
        os.close(fd)
    except OSError:
        pass
							

可用性:Unix Windows。

os. device_encoding ( fd )

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

os. dup ( fd )

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

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

可用性:Unix Windows。

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

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

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

可用性:Unix Windows。

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

os. fchmod ( fd , mode )

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

可用性:Unix。

os. fchown ( fd , uid , gid )

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

可用性:Unix。

os. fdatasync ( fd )

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

可用性:Unix。

注意

该函数不可用于 MacOS。

os. fpathconf ( fd , name )

返回打开文件相关的系统配置信息。 name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.

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

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

可用性:Unix。

os. fstat ( fd )

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

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

另请参阅

The stat() 函数。

可用性:Unix Windows。

os. fstatvfs ( fd )

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

可用性:Unix。

os. fsync ( fd )

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

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

可用性:Unix Windows。

os. ftruncate ( fd , length )

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

可用性:Unix。

os. isatty ( fd )

返回 True 若文件描述符 fd 被打开 且已连接到像 tty 设备,否则 False .

os. lockf ( fd , cmd , len )

Apply, test or remove a POSIX lock on an open file descriptor. fd is an open file descriptor. cmd specifies the command to use - one of F_LOCK , F_TLOCK , F_ULOCK or F_TEST . len specifies the section of the file to lock.

可用性:Unix。

3.3 版新增。

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

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

可用性:Unix。

3.3 版新增。

os. lseek ( fd , pos , how )

Set the current position of file descriptor fd to position pos , modified by how : SEEK_SET or 0 to set the position relative to the beginning of the file; SEEK_CUR or 1 to set it relative to the current position; SEEK_END or 2 to set it relative to the end of the file. Return the new cursor position in bytes, starting from the beginning.

可用性:Unix Windows。

os. SEEK_SET
os. SEEK_CUR
os. SEEK_END

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

可用性:Unix Windows。

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

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

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

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

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

可用性:Unix Windows。

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

注意

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

3.3 版新增: The dir_fd 自变量。

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

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

These 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_SHLOCK
os. O_EXLOCK
os. O_CLOEXEC

These constants are only available on Unix.

3.3 版改变: 添加 O_CLOEXEC 常量。

os. O_BINARY
os. O_NOINHERIT
os. O_SHORT_LIVED
os. O_TEMPORARY
os. O_RANDOM
os. O_SEQUENTIAL
os. O_TEXT

These constants are only available on Windows.

os. O_ASYNC
os. O_DIRECT
os. O_DIRECTORY
os. O_NOFOLLOW
os. O_NOATIME
os. O_PATH
os. O_TMPFILE

These constants are GNU extensions and not present if they are not defined by the C library.

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

os. openpty ( )

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

可用性:某些风味的 Unix。

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

os. pipe ( )

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

可用性:Unix Windows。

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

os. pipe2 ( flags )

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

可用性:某些风味的 Unix。

3.3 版新增。

os. posix_fallocate ( fd , offset , len )

Ensures that enough disk space is allocated for the file specified by fd starting from offset and continuing for len 字节。

可用性:Unix。

3.3 版新增。

os. posix_fadvise ( fd , offset , len , advice )

Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations. The advice applies to the region of the file specified by fd 起始于 offset and continuing for len 字节。 advice 是某一 POSIX_FADV_NORMAL , POSIX_FADV_SEQUENTIAL , POSIX_FADV_RANDOM , POSIX_FADV_NOREUSE , POSIX_FADV_WILLNEED or POSIX_FADV_DONTNEED .

可用性:Unix。

3.3 版新增。

os. POSIX_FADV_NORMAL
os. POSIX_FADV_SEQUENTIAL
os. POSIX_FADV_RANDOM
os. POSIX_FADV_NOREUSE
os. POSIX_FADV_WILLNEED
os. POSIX_FADV_DONTNEED

Flags that can be used in advice in posix_fadvise() that specify the access pattern that is likely to be used.

可用性:Unix。

3.3 版新增。

os. pread ( fd , buffersize , offset )

Read from a file descriptor, fd , at a position of offset . It will read up to buffersize number of bytes. The file offset remains unchanged.

可用性:Unix。

3.3 版新增。

os. pwrite ( fd , str , offset )

写入 bytestring to a file descriptor, fd ,从 offset , leaving the file offset unchanged.

可用性:Unix。

3.3 版新增。

os. read ( fd , n )

读取最多 n 字节从文件描述符 fd . Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned.

可用性:Unix Windows。

注意

此函数旨在低级 I/O 且必须应用于文件描述符如返回通过 os.open() or pipe() . To read a “file object” returned by the built-in function open() 或通过 popen() or fdopen() ,或 sys.stdin ,使用其 read() or readline() 方法。

os. sendfile ( out , in , offset , count )
os. sendfile ( out , in , offset , count , [ headers , ] [ trailers , ] flags=0 )

拷贝 count 字节从文件描述符 in 到文件描述符 out 起始于 offset . Return the number of bytes sent. When EOF is reached return 0.

第一函数表示法所有平台都支持,若平台有定义 sendfile() .

在 Linux,若 offset 被给定为 None , the bytes are read from the current position of in and the position of in is updated.

The second case may be used on Mac OS X and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after 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 until the end of in is reached.

所有平台支持套接字作为 out 文件描述符,且某些平台还允许其它类型 (如:常规文件、管道)。

跨平台应用程序不应使用 headers , trailers and flags 自变量。

可用性:Unix。

3.3 版新增。

os. SF_NODISKIO
os. SF_MNOWAIT
os. SF_SYNC

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

可用性:Unix。

3.3 版新增。

os. readv ( fd , buffers )

Read from a file descriptor fd into a number of mutable 像字节对象 buffers . readv() will transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data. readv() returns the total number of bytes read (which may be less than the total capacity of all the objects).

可用性:Unix。

3.3 版新增。

os. tcgetpgrp ( fd )

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

可用性:Unix。

os. tcsetpgrp ( fd , pg )

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

可用性:Unix。

os. ttyname ( fd )

Return a string which specifies the terminal device associated with file descriptor fd 。若 fd is not associated with a terminal device, an exception is raised.

可用性:Unix。

os. write ( fd , str )

写入字节字符串按 str 到文件描述符 fd 。返回实际写入字节数。

可用性:Unix Windows。

注意

此函数旨在低级 I/O 且必须应用于文件描述符如返回通过 os.open() or pipe() . To write a “file object” returned by the built-in function open() 或通过 popen() or fdopen() ,或 sys.stdout or sys.stderr ,使用其 write() 方法。

os. writev ( fd , buffers )

Write the contents of buffers 到文件描述符 fd . buffers must be a sequence of 像字节对象 . writev() writes the contents of each object to the file descriptor and returns the total number of bytes written.

可用性:Unix。

3.3 版新增。

16.1.4.1. 查询终端的尺寸

3.3 版新增。

os. get_terminal_size ( fd=STDOUT_FILENO )

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

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

If the file descriptor is not connected to a terminal, an OSError 被引发。

shutil.get_terminal_size() is the high-level function which should normally be used, os.get_terminal_size is the low-level implementation.

可用性:Unix Windows。

class os. terminal_size

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

columns

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

lines

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

16.1.4.2. 文件描述符的继承

3.4 版新增。

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

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

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

os. get_inheritable ( fd )

Get the “inheritable” flag of the specified file descriptor (a boolean).

os. set_inheritable ( fd , 可继承 )

Set the “inheritable” flag of the specified file descriptor.

os. get_handle_inheritable ( handle )

Get the “inheritable” flag of the specified handle (a boolean).

可用性:Windows。

os. set_handle_inheritable ( handle , 可继承 )

Set the “inheritable” flag of the specified handle.

可用性:Windows。

16.1.5. 文件和目录

在某些 Unix 平台,这些函数中的很多均支持一个或多个这些特征:

  • 指定文件描述符: For some functions, the path argument can be not only a string giving a path name, but also a file descriptor. The function will then operate on the file referred to by the descriptor. (For POSIX systems, Python will call the f... version of the function.)

    You can check whether or not path can be specified as a file descriptor on your platform using os.supports_fd . If it is unavailable, using it will raise a NotImplementedError .

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

  • paths relative to directory descriptors: dir_fd 不是 None , it should be a file descriptor referring to a directory, and the path to operate on should be relative; path will then be relative to that directory. If the path is absolute, dir_fd is ignored. (For POSIX systems, Python will call the ...at or f...at version of the function.)

    You can check whether or not dir_fd is supported on your platform using os.supports_dir_fd . If it is unavailable, using it will raise a NotImplementedError .

os. access ( path , mode , * , dir_fd=None , effective_ids=False , follow_symlinks=True )

Use the real uid/gid to test for access to path . Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path . mode 应该为 F_OK to test the existence of path , or it can be the inclusive OR of one or more of R_OK , W_OK ,和 X_OK to test permissions. Return True if access is allowed, False if not. See the Unix man page access(2) 了解更多信息。

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

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

可用性:Unix Windows。

注意

使用 access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:

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

is better written as:

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
					

注意

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

3.3 版改变: 添加 dir_fd , effective_ids ,和 follow_symlinks 参数。

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

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

os. chdir ( path )

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

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

可用性:Unix Windows。

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

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

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

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

可用性:Unix。

3.3 版新增: The follow_symlinks 自变量。

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

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

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

可用性:Unix Windows。

注意

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

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

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

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

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

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

可用性:Unix。

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

os. chroot ( path )

Change the root directory of the current process to path .

可用性:Unix。

os. fchdir ( fd )

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

可用性:Unix。

os. getcwd ( )

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

可用性:Unix Windows。

os. getcwdb ( )

Return a bytestring representing the current working directory.

可用性:Unix Windows。

os. lchflags ( path , flags )

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

可用性:Unix。

os. lchmod ( path , mode )

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

可用性:Unix。

os. lchown ( path , uid , gid )

更改所有者和组 ID 为 path 到数值 uid and gid . This function will not follow symbolic links. As of Python 3.3, this is equivalent to os.chown(path, uid, gid, follow_symlinks=False) .

可用性:Unix。

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

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

可用性:Unix Windows。

3.2 版改变: 添加 Windows 支持。

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

os. listdir ( path='.' )

返回包含条目名称的列表,在给定目录 path 。列表采用任意次序,且不包括特殊条目 '.' and '..' 即使它们呈现于目录中。

path may be either of type str or of type bytes 。若 path 是类型 bytes , the filenames returned will also be of type bytes ;在所有其它情况下,它们会是类型 str .

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

注意

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

可用性:Unix Windows。

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

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

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

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

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

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

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

另请参阅

The stat() 函数。

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

3.3 版改变: 添加 dir_fd 参数。

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

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

在某些系统, mode is ignored. Where it is used, the current umask value is first masked out. If the directory already exists, OSError 被引发。

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

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

可用性:Unix Windows。

3.3 版新增: The dir_fd 自变量。

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

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

默认 mode is 0o777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.

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

注意

makedirs() 会变得困惑若要创建的路径元素包含 pardir (eg. ”..” on UNIX systems).

此函数正确处理 UNC 路径。

3.2 版新增: The exist_ok 参数。

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

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

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

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

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

可用性:Unix。

3.3 版新增: The dir_fd 自变量。

os. mknod ( path , mode=0o600 , device=0 , * , dir_fd=None )

Create a filesystem node (file, device special file or named pipe) named path . mode specifies both the permissions to use and the type of node to be created, being combined (bitwise OR) with one of stat.S_IFREG , stat.S_IFCHR , stat.S_IFBLK ,和 stat.S_IFIFO (those constants are available in stat ). For stat.S_IFCHR and stat.S_IFBLK , device defines the newly created device special file (probably using os.makedev() ),否则被忽略。

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

3.3 版新增: The dir_fd 自变量。

os. major ( device )

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

os. minor ( device )

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

os. makedev ( major , minor )

Compose a raw device number from the major and minor device numbers.

os. pathconf ( path , name )

Return system configuration information relevant to a named file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.

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

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

可用性:Unix。

os. pathconf_names

字典映射的名称接受通过 pathconf() and fpathconf() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.

可用性:Unix。

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

path is a string object, the result will also be a string object, and the call may raise an UnicodeDecodeError. If the path is a bytes object, the result will be a bytes object.

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

可用性:Unix、Windows

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

3.3 版新增: The dir_fd 自变量。

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

移除 (删除) 文件 path 。若 path is a directory, OSError 被引发。使用 rmdir() to remove directories.

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

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

This function is identical to unlink() .

可用性:Unix Windows。

3.3 版新增: The dir_fd 自变量。

os. removedirs ( name )

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

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

重命名文件或目录 src to dst 。若 dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file.

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

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

可用性:Unix Windows。

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

os. renames ( old , new )

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

注意

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

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

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

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

可用性:Unix Windows。

3.3 版新增。

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

移除 (删除) 目录 path . Only works when the directory is empty, otherwise, OSError is raised. In order to remove whole directory trees, shutil.rmtree() 可以使用。

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

可用性:Unix Windows。

3.3 版新增: The dir_fd 参数。

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

获取文件或文件描述符的状态。履行等效 stat() 系统调用按给定路径。 path may be specified as either a string or as an open file descriptor. Return a stat_result 对象。

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

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

范例:

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

可用性:Unix Windows。

另请参阅

fstat() and lstat() 函数。

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

class os. stat_result

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

属性:

st_mode

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

st_ino

Inode 编号。

st_dev

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

硬链接数。

st_uid

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

st_gid

文件所有者的组标识符。

st_size

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

时间戳:

st_atime

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

st_mtime

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

st_ctime

从属平台:

  • 在 Unix 是最近元数据更改时间,
  • 在 Windows 是创建时间 (以秒为单位表达)。
st_atime_ns

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

st_mtime_ns

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

st_ctime_ns

从属平台:

  • 在 Unix 是最近元数据更改时间,
  • the time of creation on Windows, expressed in nanoseconds as an integer.

另请参阅 stat_float_times() 函数。

注意

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

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

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

st_blocks

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

st_blksize

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

st_rdev

设备类型若是 Inode 设备。

st_flags

用户为文件定义的标志。

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

st_gen

文件生成编号。

st_birthtime

文件创建的时间。

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

st_rsize

文件的实际大小。

st_creator

文件的创建者。

st_type

文件类型。

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

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

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

os. stat_float_times ( [ newvalue ] )

Determine whether stat_result represents time stamps as float objects. If newvalue is True , future calls to stat() return floats, if it is False , future calls return ints. If newvalue is omitted, return the current setting.

For compatibility with older Python versions, accessing stat_result 以元组形式始终返回整数。

Python now returns float values by default. Applications which do not work correctly with floating point time stamps can use this function to restore the old behaviour.

The resolution of the timestamps (that is the smallest possible fraction) depends on the system. Some systems only support second resolution; on these systems, the fraction will always be zero.

It is recommended that this setting is only changed at program startup time in the __main__ module; libraries should never change this setting. If an application uses a library that works incorrectly if floating point time stamps are processed, this application should turn the feature off until the library has been corrected.

从 3.3 版起弃用。

os. statvfs ( path )

履行 statvfs() system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the statvfs structure, namely: f_bsize , f_frsize , f_blocks , f_bfree , f_bavail , f_files , f_ffree , f_favail , f_flag , f_namemax .

Two module-level constants are defined for the f_flag attribute’s bit-flags: if ST_RDONLY is set, the filesystem is mounted read-only, and if ST_NOSUID is set, the semantics of setuid/setgid bits are disabled or not supported.

Additional module-level constants are defined for GNU/glibc based systems. These are ST_NODEV (disallow access to device special files), ST_NOEXEC (禁止程序执行), ST_SYNCHRONOUS (writes are synced at once), ST_MANDLOCK (allow mandatory locks on an FS), ST_WRITE (write on file/directory/symlink), ST_APPEND (仅追加文件), ST_IMMUTABLE (不可变文件), ST_NOATIME (不更新访问时间), ST_NODIRATIME (不更新目录访问时间), ST_RELATIME (相对 mtime/ctime 更新 atime)。

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

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

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

可用性:Unix。

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

os. supports_dir_fd

A Set object indicating which functions in the os module permit use of their dir_fd parameter. Different platforms provide different functionality, and an option that might work on one might be unsupported on another. For consistency’s sakes, functions that support dir_fd always allow specifying the parameter, but will raise an exception if the functionality is not actually available.

To check whether a particular function permits use of its dir_fd parameter, use the in operator on supports_dir_fd . As an example, this expression determines whether the dir_fd 参数对于 os.stat() is locally available:

os.stat in os.supports_dir_fd
							

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

3.3 版新增。

os. supports_effective_ids

A Set object indicating which functions in the os module permit use of the effective_ids parameter for os.access() . If the local platform supports it, the collection will contain os.access() , otherwise it will be empty.

To check whether you can use the effective_ids parameter for os.access() ,使用 in operator on supports_effective_ids , like so:

os.access in os.supports_effective_ids
							

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

3.3 版新增。

os. supports_fd

A Set object indicating which functions in the os module permit specifying their path parameter as an open file descriptor. Different platforms provide different functionality, and an option that might work on one might be unsupported on another. For consistency’s sakes, functions that support fd always allow specifying the parameter, but will raise an exception if the functionality is not actually available.

To check whether a particular function permits specifying an open file descriptor for its path parameter, use the in operator on supports_fd . As an example, this expression determines whether os.chdir() accepts open file descriptors when called on your local platform:

os.chdir in os.supports_fd
							

3.3 版新增。

A Set object indicating which functions in the os module permit use of their follow_symlinks parameter. Different platforms provide different functionality, and an option that might work on one might be unsupported on another. For consistency’s sakes, functions that support follow_symlinks always allow specifying the parameter, but will raise an exception if the functionality is not actually available.

To check whether a particular function permits use of its follow_symlinks parameter, use the in operator on supports_follow_symlinks . As an example, this expression determines whether the follow_symlinks 参数对于 os.stat() is locally available:

os.stat in os.supports_follow_symlinks
							

3.3 版新增。

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

On Windows, a symlink represents either a file or a directory, and does not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if target_is_directory is True or a file symlink (the default) otherwise. On non-Window platforms, target_is_directory 被忽略。

Symbolic link support was introduced in Windows 6.0 (Vista). symlink() 将引发 NotImplementedError on Windows versions earlier than 6.0.

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

注意

在 Windows, SeCreateSymbolicLinkPrivilege is required in order to successfully create symlinks. This privilege is not typically granted to regular users but is available to accounts which can escalate privileges to the administrator level. Either obtaining the privilege or running your application as an administrator are ways to successfully create symlinks.

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

可用性:Unix Windows。

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

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

os. sync ( )

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

可用性:Unix。

3.3 版新增。

os. truncate ( path , length )

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

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

可用性:Unix。

3.3 版新增。

移除 (删除) 文件 path . This function is identical to remove() unlink 名称是它的传统 Unix 名称。请参阅文档编制为 remove() 了解进一步信息。

可用性:Unix Windows。

3.3 版新增: The dir_fd 参数。

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

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

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

  • ns 被指定, it must be a 2-tuple of the form (atime_ns, mtime_ns) 各成员是表达纳秒的 int。
  • times 不是 None , it must be a 2-tuple of the form (atime, mtime) 各成员是表达秒数的 int 或浮点。
  • times is None and ns is unspecified, this is equivalent to specifying ns=(atime_ns, mtime_ns) 2 时间是当前时间。

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

Whether a directory can be given for path depends on whether the operating system implements directories as files (for example, Windows does not). Note that the exact times you set here may not be returned by a subsequent stat() 调用,从属操作系统记录访问时间和修改时间的分辨率; 见 stat() 。保留准确时间的最佳方式是使用 st_atime_ns and st_mtime_ns 字段来自 os.stat() 结果对象采用 ns 参数用于 utime .

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

可用性:Unix Windows。

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

os. walk ( top , topdown=True , onerror=None , followlinks=False )

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top 本身),它产生 3 元组 (dirpath, dirnames, filenames) .

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

若可选自变量 topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False , the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown , the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.

topdown is True , the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames ; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.

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

默认情况下, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them.

注意

Be aware that setting followlinks to True can lead to infinite recursion if a link points to a parent directory of itself. walk() does not keep track of the directories it visited already.

注意

If you pass a relative pathname, don’t change the current working directory between resumptions of walk() . walk() never changes the current directory, and assumes that its caller doesn’t either.

This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print(root, "consumes", end=" ")
    print(sum(getsize(join(root, name)) for name in files), end=" ")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories
							

In the next example (simple implementation of shutil.rmtree() ), walking the tree bottom-up is essential, rmdir() doesn’t allow deleting a directory before the directory is empty:

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))
							
os. fwalk ( top='.' , topdown=True , onerror=None , * , follow_symlinks=False , dir_fd=None )

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

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

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

注意

由于 fwalk() yields file descriptors, those are only valid until the next iteration step, so you should duplicate them (e.g. with dup() ) if you want to keep them longer.

This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:

import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
    print(root, "consumes", end="")
    print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
          end="")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories
								

In the next example, walking the tree bottom-up is essential: rmdir() doesn’t allow deleting a directory before the directory is empty:

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

可用性:Unix。

3.3 版新增。

16.1.5.1. Linux 扩展属性

3.3 版新增。

这些函数只可用于 Linux。

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

Return the value of the extended filesystem attribute 属性 for path . 属性 can be bytes or str. If it is str, it is encoded with the filesystem encoding.

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

os. listxattr ( path=None , * , follow_symlinks=True )

Return a list of the extended filesystem attributes on path . The attributes in the list are represented as strings decoded with the filesystem encoding. If path is None , listxattr() will examine the current directory.

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

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

Removes the extended filesystem attribute 属性 from path . 属性 should be bytes or str. If it is a string, it is encoded with the filesystem encoding.

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

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

Set the extended filesystem attribute 属性 on path to value . 属性 must be a bytes or str with no embedded NULs. If it is a str, it is encoded with the filesystem encoding. flags 可以是 XATTR_REPLACE or XATTR_CREATE 。若 XATTR_REPLACE is given and the attribute does not exist, EEXISTS 会被引发。若 XATTR_CREATE is given and the attribute already exists, the attribute will not be created and ENODATA 会被引发。

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

注意

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

os. XATTR_SIZE_MAX

The maximum size the value of an extended attribute can be. Currently, this is 64 KiB on Linux.

os. XATTR_CREATE

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

os. XATTR_REPLACE

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

16.1.6. 进程管理

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

The various exec* functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this is the argv[0] passed to a program’s main() 。例如, os.execv('/bin/echo', ['foo', 'bar']) 只会打印 bar on standard output; foo will seem to be ignored.

os. abort ( )

生成 SIGABRT signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns an exit code of 3 . Be aware that calling this function will not call the Python signal handler registered for SIGABRT with signal.signal() .

可用性:Unix Windows。

os. execl ( path , arg0 , arg1 , ... )
os. execle ( path , arg0 , arg1 , ... , env )
os. execlp ( file , arg0 , arg1 , ... )
os. execlpe ( file , arg0 , arg1 , ... , env )
os. execv ( path , args )
os. execve ( path , args , env )
os. execvp ( file , args )
os. execvpe ( file , args , env )

These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError 异常。

The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using sys.stdout.flush() or os.fsync() before calling an exec* 函数。

The “l” and “v” variants of the exec* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the execl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced.

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

For execle() , execlpe() , execve() ,和 execvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (these are used instead of the current process’ environment); the functions execl() , execlp() , execv() ,和 execvp() all cause the new process to inherit the environment of the current process.

For execve() on some platforms, path may also be specified as an open file descriptor. This functionality may not be supported on your platform; you can check whether or not it is available using os.supports_fd . If it is unavailable, using it will raise a NotImplementedError .

可用性:Unix Windows。

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

os. _exit ( n )

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

可用性:Unix Windows。

注意

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

The following exit codes are defined and can be used with _exit() , although they are not required. These are typically used for system programs written in Python, such as a mail server’s external command delivery program.

注意

Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.

os. EX_OK

退出代码意味着没有错误发生。

可用性:Unix。

os. EX_USAGE

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

可用性:Unix。

os. EX_DATAERR

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

可用性: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 the inability 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 had some 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 something that may not really be an error, such as a network connection that couldn’t be made during a retryable operation.

可用性:Unix。

os. EX_PROTOCOL

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

可用性:Unix。

os. EX_NOPERM

Exit code that means that there were insufficient permissions to perform the operation (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

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

可用性:Unix。

os. fork ( )

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

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

警告

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

可用性:Unix。

os. forkpty ( )

分叉子级进程,使用新的伪终端作为子级进程的控制终端。返回一对 (pid, fd) ,其中 pid is 0 in the child, the new child’s process id in the parent, and fd is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the pty 模块。若出现错误 OSError 被引发。

可用性:某些风味的 Unix。

os. kill ( pid , sig )

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

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

另请参阅 signal.pthread_kill() .

3.2 版新增: Windows 支持。

os. killpg ( pgid , sig )

发送信号 sig 给进程组 pgid .

可用性:Unix。

os. nice ( increment )

添加 increment 到进程的 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 )

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

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

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

os. spawnl ( mode , path , ... )
os. spawnle ( mode , path , ... , env )
os. spawnlp ( mode , file , ... )
os. spawnlpe ( mode , file , ... , env )
os. spawnv ( mode , path , args )
os. spawnve ( mode , path , args , env )
os. spawnvp ( mode , file , args )
os. spawnvpe ( mode , file , args , env )

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

(注意, subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the 替换较旧函数采用 subprocess 模块 章节。)

mode is P_NOWAIT , this function returns the process id of the new process; if mode is P_WAIT , returns the process’s exit code if it exits normally, or -signal ,其中 signal is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with the waitpid() 函数。

The “l” and “v” variants of the spawn* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the spawnl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run.

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

For spawnle() , spawnlpe() , spawnve() ,和 spawnvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process’ environment); the functions spawnl() , spawnlp() , spawnv() ,和 spawnvp() all cause the new process to inherit the environment of the current process. Note that keys and values in the env dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of 127 .

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

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

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

os. P_NOWAIT
os. P_NOWAITO

可能的值对于 mode 参数用于 spawn* family of functions. If either of these values is given, the spawn*() functions will return as soon as the new process has been created, with the process id as the return value.

可用性:Unix Windows。

os. P_WAIT

可能的值对于 mode 参数用于 spawn* family of functions. If this is given as mode spawn*() functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or -signal 若信号杀除进程。

可用性:Unix Windows。

os. P_DETACH
os. P_OVERLAY

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

可用性:Windows。

os. startfile ( path [ , operation ] )

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

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

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

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

可用性:Windows。

os. system ( 命令 )

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

在 Unix,返回值是进程的退出状态,指定编码格式为 wait() . Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

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

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

可用性:Unix Windows。

os. times ( )

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

  • user - 用户时间
  • system - 系统时间
  • children_user - 所有子级进程的用户时间
  • children_system - 所有子级进程的系统时间
  • elapsed - 从过去固定点起的真实消耗时间

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

见 Unix 手册页 times(2) or the corresponding Windows Platform API documentation. On Windows, only user and system are known; the other attributes are zero.

可用性:Unix Windows。

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

os. wait ( )

Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

可用性:Unix。

os. waitid ( idtype , id , 选项 )

Wait for the completion of one or more child processes. idtype 可以是 P_PID , P_PGID or P_ALL . id specifies the pid to wait on. 选项 is constructed from the ORing of one or more of WEXITED , WSTOPPED or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT . The return value is an object representing the data contained in the siginfo_t structure, namely: si_pid , si_uid , si_signo , si_status , si_code or None if WNOHANG is specified and there are no children in a waitable state.

可用性:Unix。

3.3 版新增。

os. P_PID
os. P_PGID
os. P_ALL

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

可用性:Unix。

3.3 版新增。

os. WEXITED
os. WSTOPPED
os. WNOWAIT

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

可用性:Unix。

3.3 版新增。

os. CLD_EXITED
os. CLD_DUMPED
os. CLD_TRAPPED
os. CLD_CONTINUED

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

可用性:Unix。

3.3 版新增。

os. waitpid ( pid , 选项 )

The details of this function differ on Unix and Windows.

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

pid 大于 0 , waitpid() requests status information for that specific process. If pid is 0 , the request is for the status of any child in the process group of the current process. If pid is -1 , the request pertains to any child of the current process. If pid 小于 -1 , status is requested for any process in the process group -pid (the absolute value of pid ).

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

On Windows: Wait for completion of a process given by process handle pid , and return a tuple containing pid , and its exit status shifted left by 8 bits (shifting makes cross-platform use of the function easier). A pid less than or equal to 0 has no special meaning on Windows, and raises an exception. The value of integer 选项 不起作用。 pid can refer to any process whose id is known, not necessarily a child process. The spawn* functions called with P_NOWAIT return suitable process handles.

os. wait3 ( 选项 )

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

可用性:Unix。

os. wait4 ( pid , 选项 )

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

可用性:Unix。

os. WNOHANG

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

可用性:Unix。

os. WCONTINUED

This option causes child processes to be reported if they have been continued from a job control stop since their status was last reported.

可用性:某些 Unix 系统。

os. WUNTRACED

This option causes child processes to be reported if they have been stopped but their current state has not been reported since they were stopped.

可用性:Unix。

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

os. WCOREDUMP ( status )

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

可用性:Unix。

os. WIFCONTINUED ( status )

返回 True if the process has been continued from a job control stop, otherwise return False .

可用性:Unix。

os. WIFSTOPPED ( status )

返回 True 若进程已停止,否则返回 False .

可用性:Unix。

os. WIFSIGNALED ( status )

返回 True 如果进程由于信号而退出,否则返回 False .

可用性:Unix。

os. WIFEXITED ( status )

返回 True 若退出进程使用 exit(2) 系统调用,否则返回 False .

可用性:Unix。

os. WEXITSTATUS ( status )

WIFEXITED(status) is true, return the integer parameter to the exit(2) system call. Otherwise, the return value is meaningless.

可用性:Unix。

os. WSTOPSIG ( status )

Return the signal which caused the process to stop.

可用性:Unix。

os. WTERMSIG ( status )

Return the signal which caused the process to exit.

可用性:Unix。

16.1.7. 接口到调度器

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

3.3 版新增。

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

os. SCHED_OTHER

默认调度策略。

os. SCHED_BATCH

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

os. SCHED_IDLE

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

os. SCHED_SPORADIC

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

os. SCHED_FIFO

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

os. SCHED_RR

循环调度策略。

os. SCHED_RESET_ON_FORK

This flag can OR’ed with any other scheduling policy. When a process with this flag set forks, its child’s scheduling policy and priority are reset to the default.

class os. sched_param ( sched_priority )

This class represents tunable scheduling parameters used in sched_setparam() , sched_setscheduler() ,和 sched_getparam() . It is immutable.

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

sched_priority

调度策略的调度优先级。

os. sched_get_priority_min ( policy )

Get the minimum priority value for policy . policy is one of the scheduling policy constants above.

os. sched_get_priority_max ( policy )

Get the maximum priority value for policy . policy is one of the scheduling policy constants above.

os. sched_setscheduler ( pid , policy , param )

Set the scheduling policy for the process with PID pid pid of 0 means the calling process. policy is one of the scheduling policy constants above. param sched_param 实例。

os. sched_getscheduler ( pid )

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

os. sched_setparam ( pid , param )

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

os. sched_getparam ( pid )

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

os. sched_rr_get_interval ( pid )

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

os. sched_yield ( )

自愿放弃 CPU。

os. sched_setaffinity ( pid , mask )

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

os. sched_getaffinity ( pid )

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

16.1.8. 杂项系统信息

os. confstr ( name )

Return string-valued system configuration values. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the confstr_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted.

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

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

可用性:Unix。

os. confstr_names

字典映射的名称接受通过 confstr() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.

可用性:Unix。

os. cpu_count ( )

Return the number of CPUs in the system. Returns None if undetermined.

3.4 版新增。

os. getloadavg ( )

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

可用性:Unix。

os. sysconf ( name )

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

可用性:Unix。

os. sysconf_names

字典映射的名称接受通过 sysconf() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.

可用性:Unix。

下列数据值用于支持路径操纵操作。所有平台都有定义这些。

路径名的高级操作的定义在 os.path 模块。

os. curdir

The constant string used by the operating system to refer to the current directory. This is '.' for Windows and POSIX. Also available via os.path .

os. pardir

The constant string used by the operating system to refer to the parent directory. This is '..' for Windows and POSIX. Also available via os.path .

os. sep

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

os. altsep

操作系统用来分隔路径名分量的替代字符,或 None 若只存在一个分隔符。这被设为 '/' 在 Windows 系统 sep 是 反斜杠。也可用凭借 os.path .

os. extsep

The character which separates the base filename from the extension; for example, the '.' in os.py . Also available via os.path .

os. pathsep

The character conventionally used by the operating system to separate search path components (as in PATH ),譬如 ':' for POSIX or ';' 为 Windows。也可用凭借 os.path .

os. defpath

The default search path used by exec*p* and spawn*p* if the environment doesn’t have a 'PATH' key. Also available via os.path .

os. linesep

The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows. Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' 代替,在所有平台。

os. devnull

null 设备的文件路径。例如: '/dev/null' 为 POSIX, 'nul' 为 Windows。也可用凭借 os.path .

os. RTLD_LAZY
os. RTLD_NOW
os. RTLD_GLOBAL
os. RTLD_LOCAL
os. RTLD_NODELETE
os. RTLD_NOLOAD
os. RTLD_DEEPBIND

标志用于 setdlopenflags() and getdlopenflags() 函数。见 Unix 手册页 dlopen(3) 了解不同标志的具体含义。

3.3 版新增。

16.1.9. Miscellaneous Functions

os. urandom ( n )

Return a string of n random bytes suitable for cryptographic use.

This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a Unix-like system this will query /dev/urandom , and on Windows it will use CryptGenRandom() . If a randomness source is not found, NotImplementedError 会被引发。

For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom .

版权所有  © 2014-2026 乐数软件    

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