os
— Miscellaneous operating system interfaces其他操作系统接口¶
Source code: Lib/os.py
This module provides a portable way of using operating system dependent functionality. 此模块提供了一种使用操作系统相关功能的便携式方法。If you just want to read or write a file see 如果您只想读取或写入一个文件,请参阅open()
, if you want to manipulate paths, see the os.path
module, and if you want to read all the lines in all the files on the command line see the fileinput
module. open()
;如果您想操作路径,请参阅os.path
模块;如果您想读取命令行上所有文件中的所有行,请参阅fileinput
模块。For creating temporary files and directories see the 有关创建临时文件和目录的信息,请参阅tempfile
module, and for high-level file and directory handling see the shutil
module.tempfile
模块;有关高级文件和目录处理的信息,请参阅shutil
模块。
Notes on the availability of these functions:有关这些功能可用性的说明:
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 functionPython的所有内置操作系统相关模块的设计都是这样的:只要相同的功能可用,它就使用相同的接口;例如,函数os.stat(path)
returns stat information about path in the same format (which happens to have originated with the POSIX interface).os.stat(path)
以相同的格式返回关于path的stat信息(这恰好是由POSIX接口产生的)。Extensions peculiar to a particular operating system are also available through the特定操作系统特有的扩展也可以通过os
module, but using them is of course a threat to portability.os
模块获得,但使用它们当然会威胁到可移植性。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 returned.所有接受路径或文件名的函数都接受字节和字符串对象,如果返回路径或文件名,则会生成相同类型的对象。On VxWorks, os.popen, os.fork, os.execv and os.spawn*p* are not supported.在VxWorks上,不支持os.popen、os.fork、os.execv和os.spawn*p*。
Note
All functions in this module raise 如果文件名和路径无效或无法访问,或者其他参数类型正确,但操作系统不接受,则此模块中的所有函数都会引发OSError
(or subclasses thereof) 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.OSError
(或其子类)。
-
os.
name
¶ The name of the operating system dependent module imported.导入的操作系统相关模块的名称。The following names have currently been registered:目前已注册以下名称:'posix'
,'nt'
,'java'
.'posix'
、'nt'
、'java'
。See also
sys.platform
has a finer granularity.粒度更细。os.uname()
gives system-dependent version information.提供与系统相关的版本信息。Theplatform
module provides detailed checks for the system’s identity.platform
模块提供系统标识的详细检查。
File Names, Command Line Arguments, and Environment Variables文件名、命令行参数和环境变量¶
In Python, file names, command line arguments, and environment variables are represented using the string type. 在Python中,文件名、命令行参数和环境变量使用字符串类型表示。On some systems, decoding these strings to and from bytes is necessary before passing them to the operating system. 在某些系统上,在将这些字符串传递到操作系统之前,需要将其与字节进行解码。Python uses the filesystem encoding and error handler to perform this conversion (see Python使用文件系统编码和错误处理程序来执行此转换(请参阅sys.getfilesystemencoding()
).sys.getfilesystemencoding()
)。
The filesystem encoding and error handler are configured at Python startup by the PyConfig_Read()
function: see filesystem_encoding
and filesystem_errors
members of PyConfig
.PyConfig_Read()
函数在Python启动时配置文件系统编码和错误处理程序:请参阅PyConfig
的filesystem_encoding
和filesystem_errors
成员。
Changed in version 3.1:版本3.1中更改: On some systems, conversion using the file system encoding may fail. 在某些系统上,使用文件系统编码的转换可能会失败。In this case, Python uses the 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.在这种情况下,Python使用代理场景编码错误处理程序,这意味着解码时不可编码的字节被Unicode字符U+DCxx替换,编码时这些字节再次转换为原始字节。
The file system encoding must guarantee to successfully decode all bytes below 128. 文件系统编码必须保证成功解码128以下的所有字节。If the file system encoding fails to provide this guarantee, API functions can raise 如果文件系统编码无法提供这种保证,API函数可能会引发UnicodeError
.UnicodeError
。
See also the locale encoding.另请参见区域设置编码。
Python UTF-8 Mode模式¶
The Python UTF-8 Mode ignores the locale encoding and forces the usage of the UTF-8 encoding:Python UTF-8模式忽略区域设置编码,并强制使用UTF-8编码:
Use UTF-8 as the filesystem encoding.使用UTF-8作为文件系统编码。sys.getfilesystemencoding()
returns返回'UTF-8'
.'UTF-8'
。locale.getpreferredencoding()
returns返回'UTF-8'
(the do_setlocale argument has no effect).'UTF-8'
(do_setlocale参数无效)。sys.stdin
,sys.stdout
, andsys.stderr
all use UTF-8 as their text encoding, with thesurrogateescape
error handler being enabled forsys.stdin
andsys.stdout
(sys.stderr
continues to usebackslashreplace
as it does in the default locale-aware mode)sys.stdin
、sys.stdout
和sys.stderr
都使用UTF-8作为文本编码,并为sys.stdin
和sys.stdout
启用了surrogateescape
surrogateescape
错误处理程序(sys.stderr
继续使用backslashreplace
,就像在默认的区域设置感知模式中一样)On Unix,在Unix上,os.device_encoding()
returns'UTF-8'
rather than the device encoding.os.device_encoding()
返回'UTF-8'
,而不是设备编码。
Note that the standard stream settings in UTF-8 mode can be overridden by 请注意,UTF-8模式下的标准流设置可以被PYTHONIOENCODING
(just as they can be in the default locale-aware mode).PYTHONIOENCODING
覆盖(就像它们可以在默认的区域设置感知模式下一样)。
As a consequence of the changes in those lower level APIs, other higher level APIs also exhibit different default behaviours:由于这些低级API的变化,其他高级API也表现出不同的默认行为:
Command line arguments, environment variables and filenames are decoded to text using the UTF-8 encoding.命令行参数、环境变量和文件名使用UTF-8编码解码为文本。os.fsdecode()
and和os.fsencode()
use the UTF-8 encoding.使用UTF-8编码。默认情况下,open()
,io.open()
, andcodecs.open()
use the UTF-8 encoding by default.open()
、io.open()
和codecs.open()
使用UTF-8编码。However, they still use the strict error handler by default so that attempting to open a binary file in text mode is likely to raise an exception rather than producing nonsense data.但是,默认情况下,它们仍然使用严格的错误处理程序,因此尝试以文本模式打开二进制文件可能会引发异常,而不是生成无意义的数据。
The Python UTF-8 Mode is enabled if the LC_CTYPE locale is 如果在Python启动时LC_CTYPE区域设置为C
or POSIX
at Python startup (see the PyConfig_Read()
function).C
或POSIX
,则启用Python UTF-8模式(请参阅PyConfig_Read()
函数)。
It can be enabled or disabled using the 可以使用-X utf8
command line option and the PYTHONUTF8
environment variable.-X utf8
命令行选项和PYTHONUTF8
环境变量启用或禁用它。
If the 如果根本没有设置PYTHONUTF8
environment variable is not set at all, then the interpreter defaults to using the current locale settings, unless the current locale is identified as a legacy ASCII-based locale (as described for PYTHONCOERCECLOCALE
), and locale coercion is either disabled or fails. PYTHONUTF8
环境变量,那么解释器默认使用当前区域设置,除非当前区域设置被标识为基于ASCII的旧区域设置(如PYTHONCOERCECLOCALE
所述),并且区域设置强制被禁用或失败。In such legacy locales, the interpreter will default to enabling UTF-8 mode unless explicitly instructed not to do so.在这种遗留语言环境中,除非明确指示不这样做,否则解释器将默认启用UTF-8模式。
The Python UTF-8 Mode can only be enabled at the Python startup. Python UTF-8模式只能在Python启动时启用。Its value can be read from 可以从sys.flags.utf8_mode
.sys.flags.utf8_mode
读取其值。
See also the UTF-8 mode on Windows and the filesystem encoding and error handler.另请参阅Windows上的UTF-8模式以及文件系统编码和错误处理程序。
Process Parameters工艺参数¶
These functions and data items provide information and operate on the current process and user.这些函数和数据项提供信息,并对当前进程和用户进行操作。
-
os.
ctermid
()¶ Return the filename corresponding to the controlling terminal of the process.返回与进程的控制终端相对应的文件名。Availability可用性: Unix.
-
os.
environ
¶ A mapping object where keys and values are strings that represent the process environment.一个映射对象,其中键和值是表示流程环境的字符串。For example,例如,environ['HOME']
is the pathname of your home directory (on some platforms), and is equivalent togetenv("HOME")
in C.environ['HOME']
是您的主目录的路径名(在某些平台上),相当于C中的getenv("HOME")
。This mapping is captured the first time the此映射是在第一次导入os
module is imported, typically during Python startup as part of processingsite.py
.os
模块时捕获的,通常是在Python启动期间,作为处理site.py
的一部分。Changes to the environment made after this time are not reflected in在此之后对环境所做的更改不会反映在os.environ
, except for changes made by modifyingos.environ
directly.os.environ
中,但通过直接修改os.environ
所做的更改除外。This mapping may be used to modify the environment as well as query the environment.此映射可用于修改环境以及查询环境。putenv()
will be called automatically when the mapping is modified.将在修改映射时自动调用。On Unix, keys and values use在Unix上,键和值使用sys.getfilesystemencoding()
and'surrogateescape'
error handler.sys.getfilesystemencoding()
和'surrogateescape'
错误处理程序。Use如果要使用其他编码,请使用environb
if you would like to use a different encoding.environb
。Note
Calling直接调用putenv()
directly does not changeos.environ
, so it’s better to modifyos.environ
.putenv()
不会更改os.environ
,因此最好修改os.environ
。Note
On some platforms, including FreeBSD and macOS, setting在某些平台上,包括FreeBSD和macOS,设置environ
may cause memory leaks.environ
可能会导致内存泄漏。Refer to the system documentation for请参阅putenv()
.putenv()
的系统文档。You can delete items in this mapping to unset environment variables.您可以删除此映射中的项以取消设置环境变量。将在从unsetenv()
will be called automatically when an item is deleted fromos.environ
, and when one of thepop()
orclear()
methods is called.os.environ
中删除项目时,以及在调用pop()
或clear()
方法之一时自动调用unsetenv()
。
-
os.
environb
¶ Bytes version ofenviron
: a mapping object where both keys and values arebytes
objects representing the process environment.environ
的字节版本:一个映射对象,其中键和值都是表示流程环境的bytes
对象。environ
andenvironb
are synchronized (modifyingenvironb
updatesenviron
, and vice versa).environ
和environb
是同步的(修改environb
更新environ
,反之亦然)。仅当environb
is only available ifsupports_bytes_environ
isTrue
.supports_bytes_environ
为True
时,environb
才可用。New in version 3.2.版本3.2中新增。
-
os.
chdir
(path) -
os.
fchdir
(fd) -
os.
getcwd
() These functions are described in Files and Directories.这些函数在文件和目录中进行了描述。
-
os.
fsencode
(filename)¶ Encode path-like filename to the filesystem encoding and error handler; return将类似路径文filename编码到文件系统编码和错误处理程序;返回bytes
unchanged.bytes
不变。fsdecode()
is the reverse function.是逆函数。New in version 3.2.版本3.2中新增。Changed in version 3.6:版本3.6中更改:Support added to accept objects implementing the添加了支持以接受实现os.PathLike
interface.os.PathLike
接口的对象。
-
os.
fsdecode
(filename)¶ Decode the path-like filename from the filesystem encoding and error handler; return从文件系统编码和错误处理程序中解码类似路径的filename;返回str
unchanged.str
不变。fsencode()
is the reverse function.是逆函数。New in version 3.2.版本3.2中新增。Changed in version 3.6:版本3.6中更改:Support added to accept objects implementing the添加了支持,以接受实现os.PathLike
interface.os.PathLike
接口的对象。
-
os.
fspath
(path)¶ Return the file system representation of the path.返回路径的文件系统表示形式。If如果传入str
orbytes
is passed in, it is returned unchanged.str
或bytes
,则返回时保持不变。Otherwise否则调用__fspath__()
is called and its value is returned as long as it is astr
orbytes
object.__fspath__()
并返回其值,只要它是str或bytes对象。In all other cases,在所有其他情况下,都会引发TypeError
is raised.TypeError
。New in version 3.6.版本3.6中新增。
-
class
os.
PathLike
¶ An abstract base class for objects representing a file system path, e.g.表示文件系统路径的对象的抽象基类,例如pathlib.PurePath
.pathlib.PurePath
。New in version 3.6.版本3.6中新增。
-
os.
getenv
(key, default=None)¶ Return the value of the environment variable key if it exists, or default if it doesn’t.如果环境变量key存在,则返回其值;如果不存在,则返回其default。key, default and the result are str.key、default和结果为str。On Unix, keys and values are decoded with在Unix上,键和值使用sys.getfilesystemencoding()
and'surrogateescape'
error handler.sys.getfilesystemencoding()
和'surrogateescape'
错误处理程序进行解码。Use如果要使用不同的编码,请使用os.getenvb()
if you would like to use a different encoding.os.getenvb()
。Availability可用性: most flavors of Unix, Windows.:大多数Unix和Windows版本。
-
os.
getenvb
(key, default=None)¶ Return the value of the environment variable key if it exists, or default if it doesn’t.如果环境变量key存在,则返回其值;如果不存在,则返回其default。key, default and the result are bytes.key、default和结果均为字节。getenvb()
is only available if仅当supports_bytes_environ
isTrue
.supports_bytes_environ
为True
时才可用。Availability可用性: most flavors of Unix.:大多数Unix版本。New in version 3.2.版本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.返回启动进程时将搜索命名可执行文件(类似于shell)的目录列表。env, when specified, should be an environment variable dictionary to lookup the PATH in.指定env时,应为环境变量字典,以查找其中的路径。By default, when env is默认情况下,当env为None
,environ
is used.None
时,将使用environ
。New in version 3.2.版本3.2中新增。
-
os.
getegid
()¶ Return the effective group id of the current process.返回当前进程的有效组id。This corresponds to the “set id” bit on the file being executed in the current process.这对应于当前进程中正在执行的文件上的“set id”位。Availability可用性: Unix.
-
os.
geteuid
()¶ -
Return the current process’s effective user id.返回当前进程的有效用户id。Availability可用性: Unix.
-
os.
getgid
()¶ -
Return the real group id of the current process.返回当前进程的实际组id。Availability可用性: Unix.
-
os.
getgrouplist
(user, group)¶ Return list of group ids that user belongs to.返回user所属的组ID列表。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.如果group不在列表中,则将其包括在内;通常,将group指定为user密码记录中的组ID字段。Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
getgroups
()¶ Return list of supplemental group ids associated with the current process.返回与当前进程关联的补充组ID列表。Availability可用性: Unix.Note
On macOS,在macOS上,getgroups()
behavior differs somewhat from other Unix platforms.getgroups()
的行为与其他Unix平台有所不同。If the Python interpreter was built with a deployment target of如果Python解释器是使用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 tosetgroups()
if suitably privileged.10.5
或更早版本的部署目标构建的,则getgroups()
返回与当前用户进程相关联的有效组ID列表;该列表仅限于系统定义的条目数,通常为16个,如果有适当的特权,可以通过调用setgroups()
来修改。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 tosetgroups()
, and its length is not limited to 16.10.5
的部署目标构建,则getgroups()
返回与进程的有效用户id相关联的用户的当前组访问列表;组访问列表可能在进程的生命周期内发生变化,它不受对setgroups()
的调用的影响,并且其长度不限于16。The deployment target value,部署目标值MACOSX_DEPLOYMENT_TARGET
, can be obtained withsysconfig.get_config_var()
.MACOSX_DEPLOYMENT_TARGET
可以通过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在大多数情况下,使用getpass.getuser()
since the latter checks the environment variablesLOGNAME
orUSERNAME
to find out who the user is, and falls back topwd.getpwuid(os.getuid())[0]
to get the login name of the current real user id.getpass.getuser()
更有用,因为后者检查环境变量LOGNAME
或USERNAME
以确定用户是谁,并返回到pwd.getpwuid(os.getuid())[0]
以获取当前真实用户id的登录名。Availability可用性: Unix, Windows.
-
os.
getpgid
(pid)¶ Return the process group id of the process with process id pid.返回进程id为pid的进程的进程组id。If pid is 0, the process group id of the current process is returned.如果pid为0,则返回当前进程的进程组id。Availability可用性: Unix.
-
os.
getpgrp
()¶ -
Return the id of the current process group.返回当前进程组的id。Availability可用性: Unix.
-
os.
getpid
()¶ -
Return the current process id.返回当前进程id。
-
os.
getppid
()¶ -
Return the parent’s process id.返回父进程id。When the parent process has exited, on Unix the id returned is the one of the init process (1), on Windows it is still the same id, which may be already reused by another process.父进程退出后,在Unix上返回的id是初始化进程(1)的id,在Windows上返回的id仍然是相同的id,可能已被其他进程重用。Availability可用性: Unix, Windows.Changed in version 3.2:版本3.2中更改:Added support for Windows.添加了对Windows的支持。
-
os.
getpriority
(which, who)¶ -
Get program scheduling priority.获取程序调度优先级。The value which is one ofwhich值是PRIO_PROCESS
,PRIO_PGRP
, orPRIO_USER
, and who is interpreted relative to which (a process identifier forPRIO_PROCESS
, process group identifier forPRIO_PGRP
, and a user ID forPRIO_USER
).PRIO_PROCESS
、PRIO_PGRP
或PRIO_USER
之一,who被解释为相对于which(PRIO_PROCESS
的进程标识符、PRIO_PGRP
的进程组标识符和PRIO_USER
的用户ID)。A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process.who的零值分别表示调用进程、调用进程的进程组或调用进程的实际用户ID。Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
PRIO_PROCESS
¶ -
os.
PRIO_PGRP
¶ -
os.
PRIO_USER
¶ Parameters for thegetpriority()
andsetpriority()
functions.getpriority()
和setpriority()
函数的参数。Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
getresuid
()¶ Return a tuple (ruid, euid, suid) denoting the current process’s real, effective, and saved user ids.返回一个元组(ruid、euid、suid),表示当前进程的真实、有效和保存的用户ID。Availability可用性: Unix.New in version 3.2.版本3.2中新增。
-
os.
getresgid
()¶ Return a tuple (rgid, egid, sgid) denoting the current process’s real, effective, and saved group ids.返回一个元组(rgid、egid、sgid),表示当前进程的真实、有效和保存的组ID。Availability可用性: Unix.New in version 3.2.版本3.2中新增。
-
os.
getuid
()¶ -
Return the current process’s real user id.返回当前进程的实际用户id。Availability可用性: 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.调用系统initgroups()
初始化组访问列表,其中包含指定用户名为其成员的所有组,以及指定的组id。Availability可用性: Unix.New in version 3.2.版本3.2中新增。
-
os.
putenv
(key, value)¶ -
Set the environment variable named key to the string value.将名为key的环境变量设置为字符串value。Such changes to the environment affect subprocesses started with对环境的此类更改会影响从os.system()
,popen()
orfork()
andexecv()
.os.system()
、popen()
或fork()
和execv()
开始的子流程。Assignments to items in对os.environ
are automatically translated into corresponding calls toputenv()
; however, calls toputenv()
don’t updateos.environ
, so it is actually preferable to assign to items ofos.environ
.os.environ
中项目的赋值自动转换为对putenv()
的相应调用;然而,对putenv()
的调用不会更新os.environ
,因此实际上最好将其分配给os.environ
的项。Note
On some platforms, including FreeBSD and macOS, setting在某些平台上,包括FreeBSD和macOS,设置environ可能会导致内存泄漏。environ
may cause memory leaks.Refer to the system documentation for请参阅putenv()
.putenv()
的系统文档。Raises an auditing event使用参数key、value引发审核事件os.putenv
with argumentskey
,value
.os.putenv
。Changed in version 3.9:版本3.9中更改:The function is now always available.该功能现在始终可用。
-
os.
setegid
(egid)¶ Set the current process’s effective group id.设置当前进程的有效组id。Availability可用性: Unix.
-
os.
seteuid
(euid)¶ Set the current process’s effective user id.设置当前进程的有效用户id。Availability可用性: Unix.
-
os.
setgid
(gid)¶ Set the current process’ group id.设置当前进程的组id。Availability可用性: Unix.
-
os.
setgroups
(groups)¶ Set the list of supplemental group ids associated with the current process to groups.将与当前进程关联的补充组ID列表设置为groups。groupsmust be a sequence, and each element must be an integer identifying a group.必须是序列,每个元素必须是标识组的整数。This operation is typically available only to the superuser.此操作通常仅对超级用户可用。Availability可用性: Unix.Note
On macOS, the length of groups may not exceed the system-defined maximum number of effective group ids, typically 16.在macOS上,groups的长度不得超过系统定义的有效组ID的最大数量,通常为16。See the documentation for请参阅getgroups()
for cases where it may not return the same group list set by calling setgroups().getgroups()
的文档,了解它可能无法返回通过调用setgroups()
设置的相同组列表的情况。
-
os.
setpgrp
()¶ Call the system call根据实现的版本(如果有),调用系统调用setpgrp()
orsetpgrp(0, 0)
depending on which version is implemented (if any).setpgrp()
或setpgrp(0, 0)
。See the Unix manual for the semantics.有关语义,请参阅Unix手册。Availability可用性: Unix.
-
os.
setpgid
(pid, pgrp)¶ Call the system call调用系统调用setpgid()
to set the process group id of the process with id pid to the process group with id pgrp.setpgid()
,将id为pid的进程的进程组id设置为id为pgrp的进程组。See the Unix manual for the semantics.有关语义,请参阅Unix手册。Availability可用性: Unix.
-
os.
setpriority
(which, who, priority)¶ -
Set program scheduling priority.设置程序调度优先级。The value which is one ofwhich值是PRIO_PROCESS
,PRIO_PGRP
, orPRIO_USER
, and who is interpreted relative to which (a process identifier forPRIO_PROCESS
, process group identifier forPRIO_PGRP
, and a user ID forPRIO_USER
).PRIO_PROCESS
、PRIO_PGRP
或PRIO_USER
之一,who被相对于which解释(PRIO_PROCESS
的进程标识符、PRIO_PGRP
的进程组标识符和PRIO_USER
的用户ID)。A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process.who的零值分别表示调用进程、调用进程的进程组或调用进程的实际用户ID。priorityis a value in the range -20 to 19.是介于-20到19之间的值。The default priority is 0; lower priorities cause more favorable scheduling.默认优先级为0;优先级越低,调度越有利。Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
setregid
(rgid, egid)¶ Set the current process’s real and effective group ids.设置当前进程的真实有效组ID。Availability可用性: Unix.
-
os.
setresgid
(rgid, egid, sgid)¶ Set the current process’s real, effective, and saved group ids.设置当前进程的真实、有效和保存的组ID。Availability可用性: Unix.New in version 3.2.版本3.2中新增。
-
os.
setresuid
(ruid, euid, suid)¶ Set the current process’s real, effective, and saved user ids.设置当前进程的真实、有效和保存的用户ID。Availability可用性: Unix.New in version 3.2.版本3.2中新增。
-
os.
setreuid
(ruid, euid)¶ Set the current process’s real and effective user ids.设置当前进程的真实有效用户ID。Availability可用性: Unix.
-
os.
getsid
(pid)¶ Call the system call调用系统调用getsid()
.getsid()
。See the Unix manual for the semantics.有关语义,请参阅Unix手册。Availability可用性: Unix.
-
os.
setsid
()¶ Call the system call调用系统调用setsid()
.setsid()
。See the Unix manual for the semantics.有关语义,请参阅Unix手册。Availability可用性: Unix.
-
os.
setuid
(uid)¶ -
Set the current process’s user id.设置当前进程的用户id。Availability可用性: Unix.
-
os.
strerror
(code)¶ Return the error message corresponding to the error code in code.返回code中错误代码对应的错误消息。On platforms where在给定未知错误号时strerror()
returnsNULL
when given an unknown error number,ValueError
is raised.strerror()
返回NULL
的平台上,会引发ValueError
。
-
os.
supports_bytes_environ
¶ 如果环境的本机操作系统类型为字节,则为True
if the native OS type of the environment is bytes (eg.False
on Windows).True
(例如,在Windows上为False
)。New in version 3.2.版本3.2中新增。
-
os.
umask
(mask)¶ Set the current numeric umask and return the previous umask.设置当前数字umask并返回上一个umask。
-
os.
uname
()¶ -
Returns information identifying the current operating system.返回标识当前操作系统的信息。The return value is an object with five attributes:返回值是一个具有五个属性的对象:sysname
-operating system name操作系统名称nodename
-name of machine on network (implementation-defined)网络上的计算机名称(实现定义)release
-operating system release操作系统版本version
-operating system version操作系统版本machine
-hardware identifier硬件标识符
For backwards compatibility, this object is also iterable, behaving like a five-tuple containing为了向后兼容,该对象也是可移植的,其行为类似于一个五元组,按该顺序包含sysname
,nodename
,release
,version
, andmachine
in that order.sysname
、nodename
、release
、version
和machine
。Some systems truncate有些系统将nodename
to 8 characters or to the leading component; a better way to get the hostname issocket.gethostname()
or evensocket.gethostbyaddr(socket.gethostname())
.nodename
截断为8个字符或前导组件;获取主机名的更好方法是<socket.gethostname()
,甚至是socket.gethostbyaddr(socket.gethostname())
)。Availability可用性: recent flavors of Unix.:Unix的最新版本。Changed in version 3.3:版本3.3中更改:Return type changed from a tuple to a tuple-like object with named attributes.返回类型已从元组更改为具有命名属性的类似元组的对象。
-
os.
unsetenv
(key)¶ -
Unset (delete) the environment variable named key.取消设置(删除)名为key的环境变量。Such changes to the environment affect subprocesses started with对环境的此类更改会影响从os.system()
,popen()
orfork()
andexecv()
.os.system()
、popen()
或fork()
和execv()
开始的子流程。Deletion of items inos.environ
is automatically translated into a corresponding call tounsetenv()
; however, calls tounsetenv()
don’t updateos.environ
, so it is actually preferable to delete items ofos.environ
.os.environ
中项目的删除会自动转换为对unsetenv()
的相应调用;然而,对unsetenv()
的调用不会更新os.environ
,因此实际上最好删除os.environ
的项。Raises an auditing event使用参数os.unsetenv
with argumentkey
.key
引发审核事件os.unsetenv
。Changed in version 3.9:版本3.9中更改:The function is now always available and is also available on Windows.该功能现在始终可用,并且在Windows上也可用。
File Object Creation文件对象创建¶
These functions create new file objects. 这些函数创建新的文件对象。(See also (有关打开文件描述符的信息,请参阅open()
for opening file descriptors.)open()
-
os.
fdopen
(fd, *args, **kwargs)¶ Return an open file object connected to the file descriptor fd.返回连接到文件描述符fd的打开文件对象。This is an alias of the这是open()
built-in function and accepts the same arguments.open()
内置函数的别名,并接受相同的参数。The only difference is that the first argument of唯一的区别是fdopen()
must always be an integer.fdopen()
的第一个参数必须始终是整数。
File Descriptor Operations文件描述符操作¶
These functions operate on I/O streams referenced using file descriptors.这些函数对使用文件描述符引用的I/O流进行操作。
File descriptors are small integers corresponding to a file that has been opened by the current process. 文件描述符是与当前进程打开的文件相对应的小整数。For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. 例如,标准输入通常为文件描述符0,标准输出为1,标准错误为2。Further files opened by a process will then be assigned 3, 4, 5, and so forth. 然后,将为进程打开的其他文件分配3、4、5等。The name “file descriptor” is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors.“文件描述符”这个名字有点欺骗性;在Unix平台上,套接字和管道也由文件描述符引用。
The 如果需要,可以使用fileno()
method can be used to obtain the file descriptor associated with a file object when required. fileno()
方法获取与文件对象关联的文件描述符。Note that using the file descriptor directly will bypass the file object methods, ignoring aspects such as internal buffering of data.请注意,直接使用文件描述符将绕过文件对象方法,忽略数据的内部缓冲等方面。
-
os.
close
(fd)¶ Close file descriptor fd.关闭文件描述符fd。Note
This function is intended for low-level I/O and must be applied to a file descriptor as returned by此函数用于低级输入/输出,必须应用于os.open()
orpipe()
.os.open()
或pipe()
返回的文件描述符。To close a “file object” returned by the built-in function要关闭由内置函数open()
or bypopen()
orfdopen()
, use itsclose()
method.open()
或popen()
或fdopen()
返回的“文件对象”,请使用其close()
方法。
-
os.
closerange
(fd_low, fd_high)¶ Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors.关闭从fd_low 包含)到fd_high(排除)的所有文件描述符,忽略错误。Equivalent to (but much faster than):相当于(但快得多):for fd in range(fd_low, fd_high):
try:
os.close(fd)
except OSError:
pass
-
os.
copy_file_range
(src, dst, count, offset_src=None, offset_dst=None)¶ Copy count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst.将count字节从文件描述符src(从偏移量offset_src开始)复制到文件描述符dst(从偏移量offset_dst开始)。If offset_src is None, then src is read from the current position; respectively for offset_dst.如果offset_src为None
,则从当前位置读取src;分别用于offset_dst。The files pointed by src and dst must reside in the same filesystem, otherwise ansrc和dst指向的文件必须位于同一个文件系统中,否则会引发OSError
is raised witherrno
set toerrno.EXDEV
.OSError
,并将errno
设置为errno.EXDEV
。This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel.这种复制是在不增加将数据从内核传输到用户空间然后再返回内核的额外成本的情况下完成的。Additionally, some filesystems could implement extra optimizations.此外,一些文件系统可以实现额外的优化。The copy is done as if both files are opened as binary.复制就像两个文件都以二进制文件打开一样进行。The return value is the amount of bytes copied.返回值是复制的字节数。This could be less than the amount requested.这可能低于要求的金额。Availability可用性: Linux kernel >= 4.5 or glibc >= 2.27.New in version 3.8.版本3.8中新增。
-
os.
device_encoding
(fd)¶ Return a string describing the encoding of the device associated with fd if it is connected to a terminal; else return如果fd连接到终端,则返回描述与fd关联的设备编码的字符串;否则返回None
.None
。On Unix, if the Python UTF-8 Mode is enabled, return在Unix上,如果启用了Python UTF-8模式,则返回'UTF-8'
rather than the device encoding.'UTF-8'
,而不是设备编码。Changed in version 3.10:版本3.10中更改:On Unix, the function now implements the Python UTF-8 Mode.在Unix上,该函数现在实现Python UTF-8模式。
-
os.
dup
(fd)¶ Return a duplicate of file descriptor fd.返回文件描述符fd的副本。The new file descriptor is non-inheritable.新文件描述符不可继承。On Windows, when duplicating a standard stream (0: stdin, 1: stdout, 2: stderr), the new file descriptor is inheritable.在Windows上,复制标准流(0:stdin、1:stdout、2:stderr)时,新的文件描述符是可继承的。Changed in version 3.4:版本3.4中更改:The new file descriptor is now non-inheritable.新文件描述符现在不可继承。
-
os.
dup2
(fd, fd2, inheritable=True)¶ Duplicate file descriptor fd to fd2, closing the latter first if necessary.将文件描述符fd复制到fd2,必要时先关闭后者。Return fd2.返回fd2。The new file descriptor is inheritable by default or non-inheritable if inheritable is默认情况下,新文件描述符是可继承的,如果inheritable为False
.False
,则该描述符是不可继承的。Changed in version 3.4:版本3.4中更改:Add the optional inheritable parameter.添加可选的inheritable参数。Changed in version 3.7:版本3.7中更改:Return fd2 on success.成功时返回fd2。Previously,以前,始终返回None
was always returned.None
。
-
os.
fchmod
(fd, mode)¶ Change the mode of the file given by fd to the numeric mode.将fd提供的文件模式更改为数字模式。See the docs for有关mode的可能值,请参阅chmod()
for possible values of mode.chmod()
的文档。As of Python 3.3, this is equivalent to从Python 3.3开始,这相当于os.chmod(fd, mode)
.os.chmod(fd, mode)
。Raises an auditing event使用参数os.chmod
with argumentspath
,mode
,dir_fd
.path
、mode
、dir_fd
引发审核事件os.chmod
。Availability可用性: Unix.
-
os.
fchown
(fd, uid, gid)¶ Change the owner and group id of the file given by fd to the numeric uid and gid.将fd给定的文件的所有者和组id更改为数字uid和gid。To leave one of the ids unchanged, set it to -1.要保持其中一个ID不变,请将其设置为-1。See请参见chown()
.chown()
。As of Python 3.3, this is equivalent to从Python 3.3开始,这相当于os.chown(fd, uid, gid)
.os.chown(fd, uid, gid)
。Raises an auditing event引发包含参数os.chown
with argumentspath
,uid
,gid
,dir_fd
.path
、uid
、gid
、dir_fd
的审核事件os.chown
。Availability可用性: Unix.
-
os.
fdatasync
(fd)¶ Force write of file with filedescriptor fd to disk.将带有文件描述符fd
的文件强制写入磁盘。Does not force update of metadata.不强制更新元数据。Availability可用性: Unix.Note
This function is not available on MacOS.此功能在MacOS上不可用。
-
os.
fpathconf
(fd, name)¶ Return system configuration information relevant to an open file.返回与打开的文件相关的系统配置信息。namespecifies 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).指定要检索的配置值;它可以是一个字符串,是定义的系统值的名称;许多标准(POSIX.1、Unix 95、Unix 98和其他标准)都指定了这些名称。Some platforms define additional names as well.一些平台还定义了其他名称。The names known to the host operating system are given in the主机操作系统已知的名称在pathconf_names
dictionary.pathconf_names
字典中给出。For configuration variables not included in that mapping, passing an integer for name is also accepted.对于该映射中未包含的配置变量,也可以为name传递整数。If name is a string and is not known,如果name是字符串且未知,则会引发ValueError
is raised.ValueError
。If a specific value for name is not supported by the host system, even if it is included in如果主机系统不支持name的特定值,即使它包含在pathconf_names
, anOSError
is raised witherrno.EINVAL
for the error number.pathconf_names
中,也会引发一个OSError
,错误号为errno.EINVAL
。As of Python 3.3, this is equivalent to从Python 3.3开始,这相当于os.pathconf(fd, name)
.os.pathconf(fd, name)
。Availability可用性: Unix.
-
os.
fstat
(fd)¶ Get the status of the file descriptor fd.获取文件描述符fd的状态。Return a返回stat_result
object.stat_result
对象。As of Python 3.3, this is equivalent to从Python 3.3开始,这相当于os.stat(fd)
.os.stat(fd)
。
-
os.
fstatvfs
(fd)¶ Return information about the filesystem containing the file associated with file descriptor fd, like返回有关包含与文件描述符fd关联的文件的文件系统的信息,如statvfs()
.statvfs()
。As of Python 3.3, this is equivalent to从Python 3.3开始,这相当于os.statvfs(fd)
.os.statvfs(fd)
。Availability可用性: Unix.
-
os.
fsync
(fd)¶ Force write of file with filedescriptor fd to disk.将带有文件描述符fd的文件强制写入磁盘。On Unix, this calls the native在Unix上,这将调用本机fsync()
function; on Windows, the MS_commit()
function.fsync()
函数;在Windows上,MS_commit()
函数。If you’re starting with a buffered Python file object f, first do如果从缓冲的Python文件对象f开始,首先执行f.flush()
, and then doos.fsync(f.fileno())
, to ensure that all internal buffers associated with f are written to disk.f.flush()
,然后执行os.fsync(f.fileno())
,以确保与f相关的所有内部缓冲区都写入磁盘。Availability可用性: Unix, Windows.
-
os.
ftruncate
(fd, length)¶ Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size.截断与文件描述符fd对应的文件,使其最大长度为个字节。As of Python 3.3, this is equivalent to从Python 3.3开始,这相当于os.truncate(fd, length)
.os.truncate(fd, length)
。Raises an auditing event使用参数fd,length引发审核事件os.truncate
with argumentsfd
,length
.os.truncate
。Availability可用性: Unix, Windows.Changed in version 3.5:版本3.5中更改:Added support for Windows添加了对Windows的支持
-
os.
get_blocking
(fd)¶ Get the blocking mode of the file descriptor:获取文件描述符的阻塞模式:如果设置了False
if theO_NONBLOCK
flag is set,True
if the flag is cleared.O_NONBLOCK
标志,则为False
;如果清除了该标志,则为True
。See also另请参见set_blocking()
andsocket.socket.setblocking()
.set_blocking()
和socket.socket.setblocking()
。Availability可用性: Unix.New in version 3.5.版本3.5中新增。
-
os.
isatty
(fd)¶ Return如果文件描述符fd打开并连接到tty(-like)设备,则返回True
if the file descriptor fd is open and connected to a tty(-like) device, elseFalse
.True
,否则返回False
。
-
os.
lockf
(fd, cmd, len)¶ Apply, test or remove a POSIX lock on an open file descriptor.在打开的文件描述符上应用、测试或删除POSIX锁。fd is an open file descriptor.fd是一个打开的文件描述符。cmd specifies the command to use - one ofcmd指定要使用的命令-F_LOCK
,F_TLOCK
,F_ULOCK
orF_TEST
.F_LOCK
、F_TLOCK
、F_ULOCK
或F_TEST
中的一个。len specifies the section of the file to lock.len指定要锁定的文件部分。Raises an auditing event使用参数os.lockf
with argumentsfd
,cmd
,len
.fd
、cmd
、len
引发审核事件os.lockf
。Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
F_LOCK
¶ -
os.
F_TLOCK
¶ -
os.
F_ULOCK
¶ -
os.
F_TEST
¶ Flags that specify what action指定lockf()
will take.lockf()
将执行的操作的标志。Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
lseek
(fd, pos, how)¶ Set the current position of file descriptor fd to position pos, modified by how:将文件描述符fd的当前位置设置为位置pos,由how修改:SEEK_SET
or0
to set the position relative to the beginning of the file;SEEK_CUR
or1
to set it relative to the current position;SEEK_END
or2
to set it relative to the end of the file.SEEK_SET
或0
设置相对于文件开头的位置;SEEK_CUR
或1
,将其设置为相对于当前位置;SEEK_END
或2
将其设置为相对于文件末尾。Return the new cursor position in bytes, starting from the beginning.返回以字节为单位的新光标位置,从头开始。
-
os.
SEEK_SET
¶ -
os.
SEEK_CUR
¶ -
os.
SEEK_END
¶ Parameters to thelseek()
function.lseek()
函数的参数。Their values are 0, 1, and 2, respectively.其值分别为0、1和2。New in version 3.3.版本3.3中新增。Some operating systems could support additional values, like一些操作系统可以支持其他值,如os.SEEK_HOLE
oros.SEEK_DATA
.os.SEEK_HOLE
或os.SEEK_DATA
。
-
os.
open
(path, flags, mode=511, *, dir_fd=None)¶ Open the file path and set various flags according to flags and possibly its mode according to mode. When computing mode, the current umask value is 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
andO_WRONLY
) are defined in theos
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.该函数可以支持相对于带有dir_fd参数的目录描述符的路径。Raises an auditing event
open
with argumentspath
,mode
,flags
.Changed in version 3.4:版本3.4中更改:The new file descriptor is now non-inheritable.新文件描述符现在不可继承。Note
This function is intended for low-level I/O. For normal usage, use the built-in function
open()
, which returns a file object withread()
andwrite()
methods (and many more). To wrap a file descriptor in a file object, usefdopen()
.New in version 3.3.版本3.3中新增。The dir_fd argument.dir_fd参数。Changed in version 3.5:版本3.5中更改: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising anInterruptedError
exception (see PEP 475 for the rationale).Changed in version 3.6:版本3.6中更改:Accepts a path-like object.接受类似路径的对象。
The following constants are options for the flags parameter to the 以下常量是open()
function. open()
函数的flags参数的选项。They can be combined using the bitwise OR operator 它们可以使用位OR运算符|
. |
组合。Some of them are not available on all platforms. 其中一些并非在所有平台上都可用。For descriptions of their availability and use, consult the open(2) manual page on Unix or 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.以上常量在Unix和Windows上可用。
-
os.
O_DSYNC
¶ -
os.
O_RSYNC
¶ -
os.
O_SYNC
¶ -
os.
O_NDELAY
¶ -
os.
O_NONBLOCK
¶ -
os.
O_NOCTTY
¶ -
os.
O_CLOEXEC
¶ The above constants are only available on Unix.以上常量仅在Unix上可用。Changed in version 3.3:版本3.3中更改: AddO_CLOEXEC
constant.
-
os.
O_BINARY
¶ -
os.
O_NOINHERIT
¶ -
os.
O_SHORT_LIVED
¶ -
os.
O_TEMPORARY
¶ -
os.
O_RANDOM
¶ -
os.
O_SEQUENTIAL
¶ -
os.
O_TEXT
¶ The above constants are only available on Windows.
-
os.
O_EVTONLY
¶ -
os.
O_FSYNC
¶ -
os.
O_SYMLINK
¶ -
os.
O_NOFOLLOW_ANY
¶ The above constants are only available on macOS.上述常数仅在macOS上可用。Changed in version 3.10:版本3.10中更改: AddO_EVTONLY
,O_FSYNC
,O_SYMLINK
andO_NOFOLLOW_ANY
constants.
-
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 by the C library.上述常量是扩展,如果不是由C库定义的,则不存在。
-
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 file descriptors are non-inheritable. For a (slightly) more portable approach, use thepty
module.Availability可用性: some flavors of Unix.Changed in version 3.4:版本3.4中更改:The new file descriptors are now non-inheritable.新的文件描述符现在是不可继承的。
-
os.
pipe
()¶ Create a pipe. Return a pair of file descriptors
(r, w)
usable for reading and writing, respectively. The new file descriptor is non-inheritable.Availability可用性: Unix, Windows.Changed in version 3.4:版本3.4中更改:The new file descriptors are now non-inheritable.新的文件描述符现在是不可继承的。
-
os.
pipe2
(flags)¶ Create a pipe with flags set atomically.使用原子设置的flags创建管道。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.Availability可用性: some flavors of Unix.New in version 3.3.版本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 bytes.
Availability可用性: Unix.New in version 3.3.版本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 starting at offset and continuing for len bytes. advice is one ofPOSIX_FADV_NORMAL
,POSIX_FADV_SEQUENTIAL
,POSIX_FADV_RANDOM
,POSIX_FADV_NOREUSE
,POSIX_FADV_WILLNEED
orPOSIX_FADV_DONTNEED
.Availability可用性: Unix.New in version 3.3.版本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.Availability可用性: Unix.New in version 3.3.版本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.返回一个包含读取字节的bytestring。If the end of the file referred to by fd has been reached, an empty bytes object is returned.如果已到达fd引用的文件的末尾,则返回空字节对象。Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
preadv
(fd, buffers, offset, flags=0)¶ Read from a file descriptor fd at a position of offset into mutable bytes-like objects buffers, leaving the file offset unchanged.
Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.将数据传输到每个缓冲区,直到其满为止,然后移动到序列中的下一个缓冲区以保存其余数据。The flags argument contains a bitwise OR of zero or more of the following flags:flags参数包含以下零个或多个标志的按位OR:Return the total number of bytes actually read which can be less than the total capacity of all the objects.返回实际读取的总字节数,该字节数可以小于所有对象的总容量。The operating system may set a limit (
sysconf()
value'SC_IOV_MAX'
) on the number of buffers that can be used.Combine the functionality of
os.readv()
andos.pread()
.Availability可用性: Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer, AIX 7.1 and newer.Using flags requires Linux 4.6 or newer.使用标志需要Linux 4.6或更新版本。New in version 3.7.版本3.7中新增。
-
os.
RWF_NOWAIT
¶ Do not wait for data which is not immediately available.不要等待无法立即获得的数据。If this flag is specified, the system call will return instantly if it would have to read data from the backing storage or wait for a lock.如果指定了此标志,则如果必须从后备存储器读取数据或等待锁定,系统调用将立即返回。If some data was successfully read, it will return the number of bytes read.如果成功读取某些数据,它将返回读取的字节数。If no bytes were read, it will return-1
and set errno toerrno.EAGAIN
.Availability可用性: Linux 4.14 and newer.New in version 3.7.版本3.7中新增。
-
os.
RWF_HIPRI
¶ High priority read/write. Allows block-based filesystems to use polling of the device, which provides lower latency, but may use additional resources.高优先级读/写。允许基于块的文件系统使用设备轮询,这提供了较低的延迟,但可能会使用其他资源。Currently, on Linux, this feature is usable only on a file descriptor opened using the
O_DIRECT
flag.Availability可用性: Linux 4.6 and newer.New in version 3.7.版本3.7中新增。
-
os.
pwrite
(fd, str, offset)¶ Write the bytestring in str to file descriptor fd at position of offset, leaving the file offset unchanged.
Return the number of bytes actually written.
Availability可用性: Unix.New in version 3.3.版本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 of bytes-like objects.
Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on.缓冲区按数组顺序处理。第一个缓冲区的全部内容在进入第二个缓冲区之前写入,依此类推。The flags argument contains a bitwise OR of zero or more of the following flags:flags参数包含以下零个或多个标志的按位OR: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()
andos.pwrite()
.Availability可用性: Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer, AIX 7.1 and newer.:Linux 2.6.30及更新版本、FreeBSD 6.0及更新版本、OpenBSD 2.7及更新版本、AIX 7.1及更新版本。Using flags requires Linux 4.7 or newer.使用标志需要Linux 4.7或更新版本。New in version 3.7.版本3.7中新增。
-
os.
RWF_DSYNC
¶ Provide a per-write equivalent of the
O_DSYNC
os.open()
flag. This flag effect applies only to the data range written by the system call.Availability可用性: Linux 4.7 and newer.New in version 3.7.版本3.7中新增。
-
os.
RWF_SYNC
¶ Provide a per-write equivalent of the
O_SYNC
os.open()
flag. This flag effect applies only to the data range written by the system call.Availability可用性: Linux 4.7 and newer.New in version 3.7.版本3.7中新增。
-
os.
RWF_APPEND
¶ Provide a per-write equivalent of the
O_APPEND
os.open()
flag. This flag is meaningful only foros.pwritev()
, and its effect applies only to the data range written by the system call. The offset argument does not affect the write operation; the data is always appended to the end of the file. However, if the offset argument is-1
, the current file offset is updated.Availability可用性: Linux 4.16 and newer.New in version 3.10.版本3.10中新增。
-
os.
read
(fd, n)¶ Read at most n bytes from file descriptor fd.
Return a bytestring containing the bytes read.返回包含读取字节的bytestring。If the end of the file referred to by fd has been reached, an empty bytes object is returned.如果已到达fd引用的文件的结尾,则返回空字节对象。Note
This function is intended for low-level I/O and must be applied to a file descriptor as returned by
os.open()
orpipe()
. To read a “file object” returned by the built-in functionopen()
or bypopen()
orfdopen()
, orsys.stdin
, use itsread()
orreadline()
methods.Changed in version 3.5:版本3.5中更改: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising anInterruptedError
exception (see PEP 475 for the rationale).
-
os.
sendfile
(out_fd, in_fd, offset, count)¶ -
os.
sendfile
(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0) Copy count bytes from file descriptor in_fd to file descriptor out_fd starting at offset.
Return the number of bytes sent.返回发送的字节数。When EOF is reached return当达到EOF时,返回0
.0
。The first function notation is supported by all platforms that define定义sendfile()
.sendfile()
的所有平台都支持第一个函数表示法。On Linux, if offset is given as
None
, the bytes are read from the current position of in_fd and the position of in_fd is updated.The second case may be used on macOS and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after the data from in_fd is written.
It returns the same as the first case.它返回与第一个案例相同的结果。On macOS and FreeBSD, a value of
0
for count specifies to send until the end of in_fd is reached.All platforms support sockets as out_fd file descriptor, and some platforms allow other types (e.g. regular file, pipe) as well.
Cross-platform applications should not use headers, trailers and flags arguments.
Availability可用性: Unix.Note
For a higher-level wrapper of
sendfile()
, seesocket.socket.sendfile()
.New in version 3.3.版本3.3中新增。Changed in version 3.9:版本3.9中更改: Parameters out and in was renamed to out_fd and in_fd.
-
os.
set_blocking
(fd, blocking)¶ Set the blocking mode of the specified file descriptor. Set the
O_NONBLOCK
flag if blocking isFalse
, clear the flag otherwise.See also
get_blocking()
andsocket.socket.setblocking()
.Availability可用性: Unix.New in version 3.5.版本3.5中新增。
-
os.
SF_NODISKIO
¶ -
os.
SF_MNOWAIT
¶ -
os.
SF_SYNC
¶ Parameters to thesendfile()
function, if the implementation supports them.sendfile()
函数的参数(如果实现支持)。Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
splice
(src, dst, count, offset_src=None, offset_dst=None)¶ Transfer count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst.将count字节从文件描述符src(从偏移量offset_src开始)传输到文件描述符dst(从偏移量offset_dst开始)。At least one of the file descriptors must refer to a pipe.至少有一个文件描述符必须引用管道。If offset_src is None, then src is read from the current position; respectively for offset_dst.如果offset_src为None
,则从当前位置读取src;分别用于offset_dst。The offset associated to the file descriptor that refers to a pipe must be与引用管道的文件描述符相关联的偏移量必须为None
.None
。The files pointed by src and dst must reside in the same filesystem, otherwise ansrc和dst指向的文件必须位于同一个文件系统中,否则会引发OSError
is raised witherrno
set toerrno.EXDEV
.OSError
,并将errno
设置为errno.EXDEV
。This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel.这种复制不需要额外的成本,即将数据从内核传输到用户空间,然后再返回内核。Additionally, some filesystems could implement extra optimizations.此外,一些文件系统可以实现额外的优化。The copy is done as if both files are opened as binary.复制就像两个文件都以二进制文件打开一样。Upon successful completion, returns the number of bytes spliced to or from the pipe.成功完成后,返回连接到管道或从管道连接的字节数。A return value of 0 means end of input.返回值0表示输入结束。If src refers to a pipe, then this means that there was no data to transfer, and it would not make sense to block because there are no writers connected to the write end of the pipe.如果src引用一个管道,那么这意味着没有要传输的数据,阻塞也没有意义,因为没有连接到管道写入端的写入程序。Availability可用性: Linux kernel >= 2.6.17 and glibc >= 2.5New in version 3.10.版本3.10中新增。
-
os.
readv
(fd, buffers)¶ Read from a file descriptor fd into a number of mutable bytes-like objects buffers.
Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data.将数据传输到每个缓冲区,直到其满为止,然后移动到序列中的下一个缓冲区以保存其余数据。Return the total number of bytes actually read which can be less than the total capacity of all the objects.返回实际读取的总字节数,该字节数可以小于所有对象的总容量。The operating system may set a limit (操作系统可以对可以使用的缓冲区数量设置限制(sysconf()
value'SC_IOV_MAX'
) on the number of buffers that can be used.sysconf()
值'SC_IOV_MAX'
)。Availability可用性: Unix.New in version 3.3.版本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()
).Availability可用性: 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()
) to pg.Availability可用性: Unix.
-
os.
ttyname
(fd)¶ Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised.
Availability可用性: Unix.
-
os.
write
(fd, str)¶ Write the bytestring in str to file descriptor fd.
Return the number of bytes actually written.
Note
This function is intended for low-level I/O and must be applied to a file descriptor as returned by此函数用于低级输入/输出,必须应用于os.open()
orpipe()
.os.open()
或pipe()
返回的文件描述符。To write a “file object” returned by the built-in functionopen()
or bypopen()
orfdopen()
, orsys.stdout
orsys.stderr
, use itswrite()
method.Changed in version 3.5:版本3.5中更改: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising anInterruptedError
exception (see PEP 475 for the rationale).
-
os.
writev
(fd, buffers)¶ Write the contents of buffers to file descriptor fd. buffers must be a sequence of bytes-like objects.
Buffers are processed in array order.缓冲区按数组顺序处理。Entire contents of the first buffer is written before proceeding to the second, and so on.第一个缓冲区的全部内容在进入第二个缓冲区之前写入,依此类推。Returns the total number of bytes actually written.返回实际写入的总字节数。The operating system may set a limit (
sysconf()
value'SC_IOV_MAX'
) on the number of buffers that can be used.Availability可用性: Unix.New in version 3.3.版本3.3中新增。
Querying the size of a terminal查询终端的大小¶
New in version 3.3.版本3.3中新增。
-
os.
get_terminal_size
(fd=STDOUT_FILENO)¶ Return the size of the terminal window as
(columns, lines)
, tuple of typeterminal_size
.The optional argument
fd
(defaultSTDOUT_FILENO
, or standard output) specifies which file descriptor should be queried.If the file descriptor is not connected to a terminal, an
OSError
is raised.shutil.get_terminal_size()
is the high-level function which should normally be used,os.get_terminal_size
is the low-level implementation.Availability可用性: Unix, Windows.
Inheritance of File Descriptors文件描述符的继承¶
New in version 3.4.版本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.自Python 3.4以来,Python创建的文件描述符在默认情况下是不可继承的。
On UNIX, non-inheritable file descriptors are closed in child processes at the execution of a new program, other file descriptors are inherited.在UNIX上,在执行新程序时,不可继承的文件描述符在子进程中被关闭,其他文件描述符则被继承。
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 parameter is False
.
-
os.
get_inheritable
(fd)¶ Get the “inheritable” flag of the specified file descriptor (a boolean).获取指定文件描述符的“可继承”标志(布尔值)。
-
os.
set_inheritable
(fd, inheritable)¶ Set the “inheritable” flag of the specified file descriptor.设置指定文件描述符的“可继承”标志。
-
os.
get_handle_inheritable
(handle)¶ Get the “inheritable” flag of the specified handle (a boolean).获取指定句柄(布尔值)的“可继承”标志。Availability可用性: Windows.
-
os.
set_handle_inheritable
(handle, inheritable)¶ Set the “inheritable” flag of the specified handle.
Availability可用性: Windows.
Files and Directories文件和目录¶
On some Unix platforms, many of these functions support one or more of these features:在某些Unix平台上,其中许多功能支持以下一个或多个功能:
specifying a file descriptor:指定文件描述符: Normally the path argument provided to functions in theos
module must be a string specifying a file path. However, some functions now alternatively accept an open file descriptor for their path argument. The function will then operate on the file referred to by the descriptor. (For POSIX systems, Python will call the variant of the function prefixed withf
(e.g. callfchdir
instead ofchdir
).)You can check whether or not path can be specified as a file descriptor for a particular function on your platform using
os.supports_fd
. If this functionality is unavailable, using it will raise aNotImplementedError
.If the function also supports dir_fd or follow_symlinks arguments, it’s an error to specify one of those when supplying path as a file descriptor.
paths relative to directory descriptors: If dir_fd is not
None
, it should be a file descriptor referring to a directory, and the path to operate on should be relative; path will then be relative to that directory. If the path is absolute, dir_fd is ignored. (For POSIX systems, Python will call the variant of the function with anat
suffix and possibly prefixed withf
(e.g. callfaccessat
instead ofaccess
).You can check whether or not dir_fd is supported for a particular function on your platform using
os.supports_dir_fd
. If it’s unavailable, using it will raise aNotImplementedError
.
not following symlinks: If follow_symlinks is
False
, and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself rather than the file pointed to by the link. (For POSIX systems, Python will call thel...
variant of the function.)You can check whether or not follow_symlinks is supported for a particular function on your platform using
os.supports_follow_symlinks
. If it’s unavailable, using it will raise aNotImplementedError
.
-
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 should be
F_OK
to test the existence of path, or it can be the inclusive OR of one or more ofR_OK
,W_OK
, andX_OK
to test permissions. ReturnTrue
if access is allowed,False
if not. See the Unix man page access(2) for more information.This function can support specifying paths relative to directory descriptors and not following symlinks.
If 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 usingos.supports_effective_ids
. If it is unavailable, using it will raise aNotImplementedError
.Note
Using
access()
to check if a user is authorized to e.g. open a file before actually doing so usingopen()
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()Note
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.Changed in version 3.3:版本3.3中更改: Added the dir_fd, effective_ids, and follow_symlinks parameters.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
F_OK
¶ -
os.
R_OK
¶ -
os.
W_OK
¶ -
os.
X_OK
¶ Values to pass as the mode parameter of
access()
to test the existence, 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. The descriptor must refer to an opened directory, not an open file.
This function can raise
OSError
and subclasses such asFileNotFoundError
,PermissionError
, andNotADirectoryError
.Raises an auditing event
os.chdir
with argumentpath
.New in version 3.3.版本3.3中新增。Added support for specifying path as a file descriptor on some platforms.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
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):This function can support not following symlinks.
Raises an auditing event
os.chflags
with argumentspath
,flags
.Availability可用性: Unix.New in version 3.3.版本3.3中新增。The follow_symlinks argument.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
chmod
(path, mode, *, dir_fd=None, follow_symlinks=True)¶ Change the mode of path to the numeric mode. mode may take one of the following values (as defined in the
stat
module) or bitwise ORed combinations of them:This function can support specifying a file descriptor, paths relative to directory descriptors and not following symlinks.
Note
Although Windows supports
chmod()
, you can only set the file’s read-only flag with it (via thestat.S_IWRITE
andstat.S_IREAD
constants or a corresponding integer value). All other bits are ignored.Raises an auditing event
os.chmod
with argumentspath
,mode
,dir_fd
.New in version 3.3.版本3.3中新增。Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
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. To leave one of the ids unchanged, set it to -1.
This function can support specifying a file descriptor, paths relative to directory descriptors and not following symlinks.
See
shutil.chown()
for a higher-level function that accepts names in addition to numeric ids.Raises an auditing event
os.chown
with argumentspath
,uid
,gid
,dir_fd
.Availability可用性: Unix.New in version 3.3.版本3.3中新增。Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.Changed in version 3.6:版本3.6中更改: Supports a path-like object.
-
os.
chroot
(path)¶ Change the root directory of the current process to path.
Availability可用性: Unix.Changed in version 3.6:版本3.6中更改:Accepts a path-like object.接受类似路径的对象。
-
os.
fchdir
(fd)¶ Change the current working directory to the directory represented by the file descriptor fd.将当前工作目录更改为文件描述符fd表示的目录。The descriptor must refer to an opened directory, not an open file.描述符必须引用打开的目录,而不是打开的文件。As of Python 3.3, this is equivalent to从Python 3.3开始,这相当于os.chdir(fd)
.os.chdir(fd)
。Raises an auditing event
os.chdir
with argumentpath
.Availability可用性: Unix.
-
os.
getcwd
()¶ Return a string representing the current working directory.
-
os.
getcwdb
()¶ Return a bytestring representing the current working directory.
Changed in version 3.8:版本3.8中更改: The function now uses the UTF-8 encoding on Windows, rather than the ANSI code page: see PEP 529 for the rationale. The function is no longer deprecated on Windows.
-
os.
lchflags
(path, flags)¶ Set the flags of path to the numeric flags, like
chflags()
, but do not follow symbolic links. As of Python 3.3, this is equivalent toos.chflags(path, flags, follow_symlinks=False)
.Raises an auditing event
os.chflags
with argumentspath
,flags
.Availability可用性: Unix.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
lchmod
(path, mode)¶ Change the mode of path to the numeric mode. If path is a symlink, this affects 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)
.Raises an auditing event
os.chmod
with argumentspath
,mode
,dir_fd
.Availability可用性: Unix.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
lchown
(path, uid, gid)¶ Change the owner and group id of path to the numeric 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)
.Raises an auditing event
os.chown
with argumentspath
,uid
,gid
,dir_fd
.Availability可用性: Unix.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
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 to supply paths relative to directory descriptors, and not following symlinks.
Raises an auditing event
os.link
with argumentssrc
,dst
,src_dir_fd
,dst_dir_fd
.Availability可用性: Unix, Windows.Changed in version 3.2:版本3.2中更改: Added Windows support.New in version 3.3.版本3.3中新增。Added the src_dir_fd, dst_dir_fd, and follow_symlinks arguments.Changed in version 3.6:版本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 by path. The list is in arbitrary order, and does not include the special entries
'.'
and'..'
even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.path may be a path-like object. If path is of type
bytes
(directly or indirectly through thePathLike
interface), the filenames returned will also be of typebytes
; in all other circumstances, they will be of typestr
.This function can also support specifying a file descriptor; the file descriptor must refer to a directory.
Raises an auditing event
os.listdir
with argumentpath
.Note
To encode
str
filenames tobytes
, usefsencode()
.See also
The
scandir()
function returns directory entries along with file attribute information, giving better performance for many common use cases.Changed in version 3.2:版本3.2中更改: The path parameter became optional.New in version 3.3.版本3.3中新增。Added support for specifying path as an open file descriptor.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
lstat
(path, *, dir_fd=None)¶ Perform the equivalent of an
lstat()
system call on the given path. Similar tostat()
, but does not follow symbolic links. Return astat_result
object.On platforms that do not support symbolic links, this is an alias for
stat()
.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.
See also
The
stat()
function.Changed in version 3.2:版本3.2中更改: Added support for Windows 6.0 (Vista) symbolic links.Changed in version 3.3:版本3.3中更改: Added the dir_fd parameter.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.Changed in version 3.8:版本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 as forstat()
.
-
os.
mkdir
(path, mode=511, *, dir_fd=None)¶ Create a directory named path with numeric mode mode.
If the directory already exists,
FileExistsError
is raised. If a parent directory in the path does not exist,FileNotFoundError
is raised.On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If bits other than the last 9 (i.e. the last 3 digits of the octal representation of the mode) are set, their meaning is platform-dependent. On some platforms, they are ignored and you should call
chmod()
explicitly to set them.This function can also support paths relative to directory descriptors.
It is also possible to create temporary directories; see the
tempfile
module’stempfile.mkdtemp()
function.Raises an auditing event
os.mkdir
with argumentspath
,mode
,dir_fd
.New in version 3.3.版本3.3中新增。The dir_fd argument.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
makedirs
(name, mode=511, exist_ok=False)¶ -
Recursive directory creation function. Like
mkdir()
, but makes all intermediate-level directories needed to contain the leaf directory.The mode parameter is passed to
mkdir()
for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invokingmakedirs()
. The file permission bits of existing parent directories are not changed.If exist_ok is
False
(the default), anFileExistsError
is raised if the target directory already exists.Note
makedirs()
will become confused if the path elements to create includepardir
(eg. “..” on UNIX systems).This function handles UNC paths correctly.
Raises an auditing event
os.mkdir
with argumentspath
,mode
,dir_fd
.New in version 3.2.版本3.2中新增。The exist_ok parameter.Changed in version 3.4.1:版本3.4.1中更改: Before Python 3.4.1, if exist_ok wasTrue
and the directory existed,makedirs()
would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.Changed in version 3.7:版本3.7中更改: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.
-
os.
mkfifo
(path, mode=438, *, 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 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 thatmkfifo()
doesn’t open the FIFO — it just creates the rendezvous point.Availability可用性: Unix.New in version 3.3.版本3.3中新增。The dir_fd argument.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
mknod
(path, mode=384, 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
, andstat.S_IFIFO
(those constants are available instat
). Forstat.S_IFCHR
andstat.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.
Availability可用性: Unix.New in version 3.3.版本3.3中新增。The dir_fd argument.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
major
(device)¶ Extract the device major number from a raw device number (usually the
st_dev
orst_rdev
field fromstat
).
-
os.
minor
(device)¶ Extract the device minor number from a raw device number (usually the
st_dev
orst_rdev
field fromstat
).
-
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.If name is a string and is not known,
ValueError
is raised. If a specific value for name is not supported by the host system, even if it is included inpathconf_names
, anOSError
is raised witherrno.EINVAL
for the error number.This function can support specifying a file descriptor.
Availability可用性: Unix.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
pathconf_names
¶ Dictionary mapping names accepted by
pathconf()
andfpathconf()
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.Availability可用性: Unix.
-
os.
readlink
(path, *, dir_fd=None)¶ Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using
os.path.join(os.path.dirname(path), result)
.If the path is a string object (directly or indirectly through a
PathLike
interface), the result will also be a string object, and the call may raise a UnicodeDecodeError. If the path is a bytes object (direct or indirectly), the result will be a bytes object.This function can also support paths relative to directory descriptors.
When trying to resolve a path that may contain links, use
realpath()
to properly handle recursion and platform differences.Availability可用性: Unix, Windows.Changed in version 3.2:版本3.2中更改: Added support for Windows 6.0 (Vista) symbolic links.New in version 3.3.版本3.3中新增。The dir_fd argument.Changed in version 3.6:版本3.6中更改: Accepts a path-like object on Unix.Changed in version 3.8:版本3.8中更改: Accepts a path-like object and a bytes object on Windows.Changed in version 3.8:版本3.8中更改: Added support for directory junctions, and changed to return the substitution path (which typically includes\\?\
prefix) rather than the optional “print name” field that was previously returned.
-
os.
remove
(path, *, dir_fd=None)¶ Remove (delete) the file path. If path is a directory, an
IsADirectoryError
is raised. Usermdir()
to remove directories. If the file does not exist, aFileNotFoundError
is raised.This function can support paths relative to directory descriptors.
On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.
This function is semantically identical to
unlink()
.Raises an auditing event
os.remove
with argumentspath
,dir_fd
.New in version 3.3.版本3.3中新增。The dir_fd argument.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
removedirs
(name)¶ -
Remove directories recursively. Works like
rmdir()
except that, if the leaf directory is successfully removed,removedirs()
tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example,os.removedirs('foo/bar/baz')
will first remove the directory'foo/bar/baz'
, and then remove'foo/bar'
and'foo'
if they are empty. RaisesOSError
if the leaf directory could not be successfully removed.Raises an auditing event
os.remove
with argumentspath
,dir_fd
.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
rename
(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶ Rename the file or directory src to dst. If dst exists, the operation will 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, an
IsADirectoryError
or aNotADirectoryError
will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, anOSError
is raised. If both are files, dst 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).This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.
If you want cross-platform overwriting of the destination, use
replace()
.Raises an auditing event
os.rename
with argumentssrc
,dst
,src_dir_fd
,dst_dir_fd
.New in version 3.3.版本3.3中新增。The src_dir_fd and dst_dir_fd arguments.Changed in version 3.6:版本3.6中更改: Accepts a path-like object for src and dst.
-
os.
renames
(old, new)¶ Recursive directory or file renaming function. Works like
rename()
, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away usingremovedirs()
.Note
This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file.
Raises an auditing event
os.rename
with argumentssrc
,dst
,src_dir_fd
,dst_dir_fd
.Changed in version 3.6:版本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 will be replaced silently if the user has permission. The operation may fail if 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 to supply paths relative to directory descriptors.
Raises an auditing event
os.rename
with argumentssrc
,dst
,src_dir_fd
,dst_dir_fd
.New in version 3.3.版本3.3中新增。Changed in version 3.6:版本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 is not empty, an
FileNotFoundError
or anOSError
is raised respectively. In order to remove whole directory trees,shutil.rmtree()
can be used.This function can support paths relative to directory descriptors.
Raises an auditing event
os.rmdir
with argumentspath
,dir_fd
.New in version 3.3.版本3.3中新增。The dir_fd parameter.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
scandir
(path='.')¶ Return an iterator of
os.DirEntry
objects corresponding to the entries in the directory given by path. The entries are yielded in arbitrary order, and the special entries'.'
and'..'
are not included. If a file is removed from or added to the directory after creating the iterator, whether an entry for that file be included is unspecified.Using
scandir()
instead oflistdir()
can significantly increase the performance of code that also needs file type or file attribute information, becauseos.DirEntry
objects expose this information if the operating system provides it when scanning a directory. Allos.DirEntry
methods may perform a system call, butis_dir()
andis_file()
usually only require a system call for symbolic links;os.DirEntry.stat()
always requires a system call on Unix but only requires one for symbolic links on Windows.path may be a path-like object. If path is of type
bytes
(directly or indirectly through thePathLike
interface), the type of thename
andpath
attributes of eachos.DirEntry
will bebytes
; in all other circumstances, they will be of typestr
.This function can also support specifying a file descriptor; the file descriptor must refer to a directory.
Raises an auditing event
os.scandir
with argumentpath
.The
scandir()
iterator supports the context manager protocol and has the following method:-
scandir.
close
()¶ Close the iterator and free acquired resources.
This is called automatically when the iterator is exhausted or garbage collected, or when an error happens during iterating. However it is advisable to call it explicitly or use the
with
statement.New in version 3.6.版本3.6中新增。
The following example shows a simple use of
scandir()
to display all the files (excluding directories) in the given path that don’t start with'.'
. Theentry.is_file()
call will generally not make an additional system call:with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_file():
print(entry.name)Note
On Unix-based systems,
scandir()
uses the system’s opendir() and readdir() functions. On Windows, it uses the Win32 FindFirstFileW and FindNextFileW functions.New in version 3.5.版本3.5中新增。New in version 3.6.版本3.6中新增。Added support for the context manager protocol and theclose()
method. If ascandir()
iterator is neither exhausted nor explicitly closed aResourceWarning
will be emitted in its destructor.The function accepts a path-like object.
Changed in version 3.7:版本3.7中更改: Added support for file descriptors on Unix.-
-
class
os.
DirEntry
¶ Object yielded by
scandir()
to expose the file path and other file attributes of a directory entry.scandir()
will provide as much of this information as possible without making additional system calls. When astat()
orlstat()
system call is made, theos.DirEntry
object will cache the result.os.DirEntry
instances are not intended to be stored in long-lived data structures; if you know the file metadata has changed or if a long time has elapsed since callingscandir()
, callos.stat(entry.path)
to fetch up-to-date information.Because the
os.DirEntry
methods can make operating system calls, they may also raiseOSError
. If you need very fine-grained control over errors, you can catchOSError
when calling one of theos.DirEntry
methods and handle as appropriate.To be directly usable as a path-like object,
os.DirEntry
implements thePathLike
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 bebytes
if thescandir()
path argument is of typebytes
andstr
otherwise. Usefsdecode()
to decode byte filenames.
-
path
¶ The entry’s full path name: equivalent to
os.path.join(scandir_path, entry.name)
where scandir_path is thescandir()
path argument. The path is only absolute if thescandir()
path argument was absolute. If thescandir()
path argument was a file descriptor, thepath
attribute is the same as thename
attribute.The
path
attribute will bebytes
if thescandir()
path argument is of typebytes
andstr
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-date information.On the first, uncached call, a system call is required on Windows but not on Unix.
-
is_dir
(*, follow_symlinks=True)¶ Return
True
if this entry is a directory or a symbolic link pointing to a directory; returnFalse
if the entry is or points to any other kind of file, or if it doesn’t exist anymore.If follow_symlinks is
False
, returnTrue
only if this entry is a directory (without following symlinks); returnFalse
if the entry 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 cache for follow_symlinksTrue
andFalse
. Callos.stat()
along withstat.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 system call, except on certain Unix file systems, such as network file systems, that return
dirent.d_type == DT_UNKNOWN
. If the entry is a symlink, a system call will be required to follow the symlink unless follow_symlinks isFalse
.This method can raise
OSError
, such asPermissionError
, butFileNotFoundError
is caught and not raised.
-
is_file
(*, follow_symlinks=True)¶ Return
True
if this entry is a file or a symbolic link pointing to a file; returnFalse
if the entry is or points to a directory or other non-file entry, or if it doesn’t exist anymore.If follow_symlinks is
False
, returnTrue
only if this entry is a file (without following symlinks); returnFalse
if the entry is a directory or other non-file entry, or if it doesn’t exist anymore.The result is cached on the
os.DirEntry
object. Caching, system calls made, and exceptions raised are as peris_dir()
.
-
is_symlink
()¶ Return
True
if this entry is a symbolic link (even if broken); returnFalse
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 on certain Unix file systems, such as network file systems, that return
dirent.d_type == DT_UNKNOWN
.This method can raise
OSError
, such asPermissionError
, butFileNotFoundError
is caught and not raised.
-
stat
(*, follow_symlinks=True)¶ Return a
stat_result
object for this entry. This method follows 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, it only requires a system call if follow_symlinks is
True
and the entry is a reparse point (for example, a symbolic link or directory junction).On Windows, the
st_ino
,st_dev
andst_nlink
attributes of thestat_result
are always set to zero. Callos.stat()
to get these attributes.The result is cached on the
os.DirEntry
object, with a separate cache for follow_symlinksTrue
andFalse
. Callos.stat()
to fetch up-to-date information.
Note that there is a nice correspondence between several attributes and methods of
os.DirEntry
and ofpathlib.Path
. In particular, thename
attribute has the same meaning, as do theis_dir()
,is_file()
,is_symlink()
andstat()
methods.New in version 3.5.版本3.5中新增。-
-
os.
stat
(path, *, dir_fd=None, follow_symlinks=True)¶ Get the status of a file or a file descriptor. Perform the equivalent of a
stat()
system call on the given path. path may be specified as either a string or bytes – directly or indirectly through thePathLike
interface – or as an open file descriptor. Return astat_result
object.This function normally follows symlinks; to stat a symlink add the argument
follow_symlinks=False
, or uselstat()
.This function can support specifying a file descriptor and not following symlinks.
On Windows, passing
follow_symlinks=False
will disable following all name-surrogate reparse points, which includes symlinks and directory junctions. Other types of reparse points that do not resemble links or that the operating system is unable to follow will be opened directly. When following a chain of multiple links, this may result in the original link being returned instead of the non-link that prevented full traversal. To obtain stat results for the final path in this case, use theos.path.realpath()
function to resolve the path name as far as possible and calllstat()
on the result. This does not apply to dangling symlinks or junction points, which will raise the usual exceptions.Example:
>>> 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
264New in version 3.3.版本3.3中新增。Added the dir_fd and follow_symlinks arguments, specifying a file descriptor instead of a path.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.Changed in version 3.8:版本3.8中更改: On Windows, all reparse points that can be resolved by the operating system are now followed, and passingfollow_symlinks=False
disables following all name surrogate reparse points. If the operating system reaches a reparse point that it is not able to follow, stat now returns 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 the
stat
structure. It is used for the result ofos.stat()
,os.fstat()
andos.lstat()
.Attributes:
-
st_mode
¶ File mode: file type and file mode bits (permissions).
-
st_ino
¶ Platform dependent, but if non-zero, uniquely identifies the file for a given value of
st_dev
. Typically:the inode number on Unix,
the file index on Windows
-
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 an integer.
-
st_ctime_ns
¶ Platform dependent:
the time of most recent metadata change on Unix,
the time of creation on Windows, expressed in nanoseconds as an integer.
Note
The exact meaning and resolution of the
st_atime
,st_mtime
, andst_ctime
attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems,st_mtime
has 2-second resolution, andst_atime
has only 1-day resolution. See your operating system documentation for details.Similarly, although
st_atime_ns
,st_mtime_ns
, andst_ctime_ns
are always expressed in nanoseconds, many systems do not provide nanosecond precision. On systems that do provide nanosecond precision, the floating-point object used to storest_atime
,st_mtime
, andst_ctime
cannot 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
, andst_ctime_ns
.On some Unix systems (such as Linux), the following attributes may also be available:
-
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 in smaller 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 be available (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 be available:
-
st_fstype
¶ String that uniquely identifies the type of the filesystem that contains the file.
On macOS 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 theBY_HANDLE_FILE_INFORMATION
structure returned byGetFileInformationByHandle()
. See theFILE_ATTRIBUTE_*
constants in thestat
module.
-
st_reparse_tag
¶ When
st_file_attributes
has theFILE_ATTRIBUTE_REPARSE_POINT
set, this field contains the tag identifying the type of reparse point. See theIO_REPARSE_TAG_*
constants in thestat
module.
The standard module
stat
defines functions and constants that are useful for extracting information from astat
structure. (On Windows, some items are filled with dummy values.)For backward compatibility, a
stat_result
instance is also accessible as a tuple of at least 10 integers giving the most important (and portable) members of thestat
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 by some implementations. For compatibility with older Python versions, accessingstat_result
as a tuple always returns integers.New in version 3.3.版本3.3中新增。Added thest_atime_ns
,st_mtime_ns
, andst_ctime_ns
members.New in version 3.5.版本3.5中新增。Added thest_file_attributes
member on Windows.Changed in version 3.5:版本3.5中更改: Windows now returns the file index asst_ino
when available.New in version 3.7.版本3.7中新增。Added thest_fstype
member to Solaris/derivatives.New in version 3.8.版本3.8中新增。Added thest_reparse_tag
member on Windows.Changed in version 3.8:版本3.8中更改: On Windows, thest_mode
member now identifies special files asS_IFCHR
,S_IFIFO
orS_IFBLK
as appropriate.-
-
os.
statvfs
(path)¶ Perform a
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 thestatvfs
structure, namely:f_bsize
,f_frsize
,f_blocks
,f_bfree
,f_bavail
,f_files
,f_ffree
,f_favail
,f_flag
,f_namemax
,f_fsid
.Two module-level constants are defined for the
f_flag
attribute’s bit-flags: ifST_RDONLY
is set, the filesystem is mounted read-only, and ifST_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
(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 access times),ST_RELATIME
(update atime relative to mtime/ctime).This function can support specifying a file descriptor.
Availability可用性: Unix.Changed in version 3.2:版本3.2中更改: TheST_RDONLY
andST_NOSUID
constants were added.New in version 3.3.版本3.3中新增。Added support for specifying path as an open file descriptor.Changed in version 3.4:版本3.4中更改: TheST_NODEV
,ST_NOEXEC
,ST_SYNCHRONOUS
,ST_MANDLOCK
,ST_WRITE
,ST_APPEND
,ST_IMMUTABLE
,ST_NOATIME
,ST_NODIRATIME
, andST_RELATIME
constants were added.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.New in version 3.7.版本3.7中新增。Addedf_fsid
.
-
os.
supports_dir_fd
¶ A
set
object indicating which functions in theos
module accept an open file descriptor for their dir_fd parameter. Different platforms provide different features, and the underlying functionality Python uses to implement the dir_fd parameter is not available on all platforms Python supports. For consistency’s sake, functions that may support dir_fd always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (SpecifyingNone
for dir_fd is always supported on all platforms.)To check whether a particular function accepts an open file descriptor for its dir_fd parameter, use the
in
operator onsupports_dir_fd
. As an example, this expression evaluates toTrue
ifos.stat()
accepts open file descriptors for dir_fd on the local platform:os.stat in os.supports_dir_fd
Currently dir_fd parameters only work on Unix platforms; none of them work on Windows.
New in version 3.3.版本3.3中新增。
-
os.
supports_effective_ids
¶ A
set
object indicating whetheros.access()
permits specifyingTrue
for its effective_ids parameter on the local platform. (SpecifyingFalse
for effective_ids is always supported on all platforms.) If the local platform supports it, the collection will containos.access()
; otherwise it will be empty.This expression evaluates to
True
ifos.access()
supportseffective_ids=True
on the local platform:os.access in os.supports_effective_ids
Currently effective_ids is only supported on Unix platforms; it does not work on Windows.
New in version 3.3.版本3.3中新增。
-
os.
supports_fd
¶ A
set
object indicating which functions in theos
module permit specifying their path parameter as an open file descriptor on the local platform. Different platforms provide different features, and the underlying functionality Python uses to accept open file descriptors as path arguments is not available on all platforms Python supports.To determine whether a particular function permits specifying an open file descriptor for its path parameter, use the
in
operator onsupports_fd
. As an example, this expression evaluates toTrue
ifos.chdir()
accepts open file descriptors for path on your local platform:os.chdir in os.supports_fd
New in version 3.3.版本3.3中新增。
-
os.
supports_follow_symlinks
¶ A
set
object indicating which functions in theos
module acceptFalse
for their follow_symlinks parameter on the local platform. Different platforms provide different features, and the underlying functionality Python uses to implement follow_symlinks is not available on all platforms Python supports. For consistency’s sake, functions that may support follow_symlinks always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (SpecifyingTrue
for follow_symlinks is always supported on all platforms.)To check whether a particular function accepts
False
for its follow_symlinks parameter, use thein
operator onsupports_follow_symlinks
. As an example, this expression evaluates toTrue
if you may specifyfollow_symlinks=False
when callingos.stat()
on the local platform:os.stat in os.supports_follow_symlinks
New in version 3.3.版本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 not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if target_is_directory is
True
or a file symlink (the default) otherwise. On non-Windows platforms, target_is_directory is ignored.This function can support paths relative to directory descriptors.
Note
On newer versions of Windows 10, unprivileged accounts can create symlinks if Developer Mode is enabled. When Developer Mode is not available/enabled, the SeCreateSymbolicLinkPrivilege privilege is required, or the process must be run as an administrator.
OSError
is raised when the function is called by an unprivileged user.Raises an auditing event
os.symlink
with argumentssrc
,dst
,dir_fd
.Availability可用性: Unix, Windows.Changed in version 3.2:版本3.2中更改: Added support for Windows 6.0 (Vista) symbolic links.New in version 3.3.版本3.3中新增。Added the dir_fd argument, and now allow target_is_directory on non-Windows platforms.Changed in version 3.6:版本3.6中更改: Accepts a path-like object for src and dst.Changed in version 3.8:版本3.8中更改: Added support for unelevated symlinks on Windows with Developer Mode.
-
os.
sync
()¶ Force write of everything to disk.
Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
truncate
(path, length)¶ Truncate the file corresponding to path, so that it is at most length bytes in size.
This function can support specifying a file descriptor.
Raises an auditing event
os.truncate
with argumentspath
,length
.Availability可用性: Unix, Windows.New in version 3.3.版本3.3中新增。Changed in version 3.5:版本3.5中更改: Added support for WindowsChanged in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
unlink
(path, *, dir_fd=None)¶ Remove (delete) the file path. This function is semantically identical to
remove()
; theunlink
name is its traditional Unix name. Please see the documentation forremove()
for further information.Raises an auditing event
os.remove
with argumentspath
,dir_fd
.New in version 3.3.版本3.3中新增。The dir_fd parameter.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
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 specifyingns=(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 subsequent
stat()
call, depending on the resolution with which your operating system records access and modification times; seestat()
. The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns fields from theos.stat()
result object with the ns parameter to utime.This function can support specifying a file descriptor, paths relative to directory descriptors and not following symlinks.
Raises an auditing event
os.utime
with argumentspath
,times
,ns
,dir_fd
.New in version 3.3.版本3.3中新增。Added support for specifying path as an open file descriptor, and the dir_fd, follow_symlinks, and ns parameters.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
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 itself), it yields a 3-tuple
(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, doos.path.join(dirpath, name)
. Whether or not the lists are sorted depends on the file system. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified.If optional argument 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 isFalse
, 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.When topdown is
True
, the caller can modify the dirnames list in-place (perhaps usingdel
or slice assignment), andwalk()
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 informwalk()
about directories the caller creates or renames before it resumeswalk()
again. Modifying dirnames when topdown isFalse
has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.By default, errors from the
scandir()
call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, anOSError
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 thefilename
attribute of the exception object.By default,
walk()
will not walk down into symbolic links that resolve to directories. Set followlinks toTrue
to visit directories pointed to by symlinks, on systems that support them.Note
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.Note
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 directoriesIn 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))Raises an auditing event
os.walk
with argumentstop
,topdown
,onerror
,followlinks
.Changed in version 3.5:版本3.5中更改: This function now callsos.scandir()
instead ofos.listdir()
, making it faster by reducing the number of calls toos.stat()
.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
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 supportsdir_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 however that, unlike other functions, the
fwalk()
default value for follow_symlinks isFalse
.Note
Since
fwalk()
yields file descriptors, those are only valid until the 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 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 directoriesIn 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)Raises an auditing event
os.fwalk
with argumentstop
,topdown
,onerror
,follow_symlinks
,dir_fd
.Availability可用性: Unix.New in version 3.3.版本3.3中新增。Changed in version 3.6:版本3.6中更改: Accepts a path-like object.Changed in version 3.7:版本3.7中更改: Added support forbytes
paths.
-
os.
memfd_create
(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 file descriptor is non-inheritable.The name supplied in name is used as a filename and will be displayed as the target of the corresponding symbolic link in the directory
/proc/self/fd/
. The displayed name is always prefixed withmemfd:
and serves only for debugging purposes. Names do not affect the behavior of the file descriptor, and as such multiple files can have the same name without any side effects.Availability可用性: Linux 3.17 or newer with glibc 2.27 or newer.New in version 3.8.版本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.New in version 3.8.版本3.8中新增。
-
os.
eventfd
(initval[, flags=os.EFD_CLOEXEC])¶ Create and return an event file descriptor. The file descriptors supports raw
read()
andwrite()
with a buffer size of 8,select()
,poll()
and similar. See man page eventfd(2) for more information. By default, the new file descriptor is non-inheritable.initval is the initial value of the event counter. The initial value must be an 32 bit unsigned integer. Please note that the initial value is limited to a 32 bit unsigned int although the event counter is an unsigned 64 bit integer with a maximum value of 264-2.
flags can be constructed from
EFD_CLOEXEC
,EFD_NONBLOCK
, andEFD_SEMAPHORE
.If
EFD_SEMAPHORE
is specified and the event counter is non-zero,eventfd_read()
returns 1 and decrements the counter by one.If
EFD_SEMAPHORE
is not specified and the event counter is non-zero,eventfd_read()
returns the current event counter value and resets the counter to zero.If the event counter is zero and
EFD_NONBLOCK
is not specified,eventfd_read()
blocks.eventfd_write()
increments the event counter. Write blocks if the write operation would increment the counter to a value larger than 264-2.Example:
import os
# semaphore with start value '1'
fd = os.eventfd(1, os.EFD_SEMAPHORE | os.EFC_CLOEXEC)
try:
# acquire semaphore
v = os.eventfd_read(fd)
try:
do_work()
finally:
# release semaphore
os.eventfd_write(fd, v)
finally:
os.close(fd)Availability可用性: Linux 2.6.27 or newer with glibc 2.8 or newer.New in version 3.10.版本3.10中新增。
-
os.
eventfd_read
(fd)¶ Read value from an
eventfd()
file descriptor and return a 64 bit unsigned int. The function does not verify that fd is aneventfd()
.Availability可用性: Seeeventfd()
New in version 3.10.版本3.10中新增。
-
os.
eventfd_write
(fd, value)¶ Add value to an
eventfd()
file descriptor. value must be a 64 bit unsigned int. The function does not verify that fd is aneventfd()
.Availability可用性: Seeeventfd()
New in version 3.10.版本3.10中新增。
-
os.
EFD_CLOEXEC
¶ Set close-on-exec flag for new
eventfd()
file descriptor.Availability可用性: Seeeventfd()
New in version 3.10.版本3.10中新增。
-
os.
EFD_NONBLOCK
¶ Set
O_NONBLOCK
status flag for neweventfd()
file descriptor.Availability可用性: Seeeventfd()
New in version 3.10.版本3.10中新增。
-
os.
EFD_SEMAPHORE
¶ Provide semaphore-like semantics for reads from a
eventfd()
file descriptor. On read the internal counter is decremented by one.Availability可用性: Linux 2.6.30 or newer with glibc 2.8 or newer.New in version 3.10.版本3.10中新增。
Linux extended attributesLinux扩展属性¶
New in version 3.3.版本3.3中新增。
These functions are all available on Linux only.这些功能仅在Linux上可用。
-
os.
getxattr
(path, attribute, *, follow_symlinks=True)¶ Return the value of the extended filesystem attribute attribute for path. attribute can be bytes or str (directly or indirectly through the
PathLike
interface). If it is str, it is encoded with the filesystem encoding.This function can support specifying a file descriptor and not following symlinks.
Raises an auditing event
os.getxattr
with argumentspath
,attribute
.Changed in version 3.6:版本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. The attributes in the list are represented as strings decoded with the filesystem encoding. If path is
None
,listxattr()
will examine the current directory.This function can support specifying a file descriptor and not following symlinks.
Raises an auditing event
os.listxattr
with argumentpath
.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
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 the
PathLike
interface). If it is a string, it is encoded with the filesystem encoding and error handler.This function can support specifying a file descriptor and not following symlinks.
Raises an auditing event
os.removexattr
with argumentspath
,attribute
.Changed in version 3.6:版本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 or indirectly through the
PathLike
interface). If it is a str, it is encoded with the filesystem encoding and error handler. flags may beXATTR_REPLACE
orXATTR_CREATE
. IfXATTR_REPLACE
is given and the attribute does not exist,ENODATA
will be raised. IfXATTR_CREATE
is given and the attribute already exists, the attribute will not be created andEEXISTS
will be raised.This function can support specifying a file descriptor and not following symlinks.
Note
A bug in Linux kernel versions less than 2.6.39 caused the flags argument to be ignored on some filesystems.
Raises an auditing event
os.setxattr
with argumentspath
,attribute
,value
,flags
.Changed in version 3.6:版本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, 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.
Process Management流程管理¶
These functions may be used to create and manage processes.
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()
. For example, os.execv('/bin/echo', ['foo', 'bar'])
will only print bar
on standard output; foo
will seem to be ignored.
-
os.
abort
()¶ Generate a
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 of3
. Be aware that calling this function will not call the Python signal handler registered forSIGABRT
withsignal.signal()
.
-
os.
add_dll_directory
(path)¶ Add a path to the DLL search path.向DLL搜索路径添加路径。This search path is used when resolving dependencies for imported extension modules (the module itself is resolved through
sys.path
), and also byctypes
.Remove the directory by calling close() on the returned object or using it in a
with
statement.See the Microsoft documentation for more information about how DLLs are loaded.
Raises an auditing event
os.add_dll_directory
with argumentpath
.Availability可用性: Windows.New in version 3.8.版本3.8中新增。Previous versions of CPython would resolve DLLs using the default behavior for the current process.以前版本的CPython将使用当前进程的默认行为解析DLL。This led to inconsistencies, such as only sometimes searchingPATH
or the current working directory, and OS functions such asAddDllDirectory
having no effect.In 3.8, the two primary ways DLLs are loaded now explicitly override the process-wide behavior to ensure consistency.在3.8中,加载DLL的两种主要方式现在显式重写了进程范围的行为,以确保一致性。See the porting notes for information on updating 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; 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
exceptions.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()
oros.fsync()
before calling anexec*
function.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 theexecl*()
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()
, andexecvpe()
) will use thePATH
environment variable to locate the program file. When the environment is being replaced (using one of theexec*e
variants, discussed in the next paragraph), the new environment is used as the source of thePATH
variable. The other variants,execl()
,execle()
,execv()
, andexecve()
, will not use thePATH
variable to locate the executable; path must contain an appropriate absolute or relative path.For
execle()
,execlpe()
,execve()
, andexecvpe()
(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 functionsexecl()
,execlp()
,execv()
, andexecvp()
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 usingos.supports_fd
. If it is unavailable, using it will raise aNotImplementedError
.Raises an auditing event
os.exec
with argumentspath
,args
,env
.Availability可用性: Unix, Windows.New in version 3.3.版本3.3中新增。Added support for specifying path as an open file descriptor forexecve()
.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
_exit
(n)¶ Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.
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.
Note
Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.
-
os.
EX_OK
¶ Exit code that means no error occurred.
Availability可用性: Unix.
-
os.
EX_USAGE
¶ Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given.
Availability可用性: Unix.
-
os.
EX_DATAERR
¶ Exit code that means the input data was incorrect.
Availability可用性: Unix.
-
os.
EX_NOINPUT
¶ Exit code that means an input file did not exist or was not readable.
Availability可用性: Unix.
-
os.
EX_NOUSER
¶ Exit code that means a specified user did not exist.
Availability可用性: Unix.
-
os.
EX_NOHOST
¶ Exit code that means a specified host did not exist.
Availability可用性: Unix.
-
os.
EX_UNAVAILABLE
¶ Exit code that means that a required service is unavailable.
Availability可用性: Unix.
-
os.
EX_SOFTWARE
¶ Exit code that means an internal software error was detected.
Availability可用性: Unix.
-
os.
EX_OSERR
¶ Exit code that means an operating system error was detected, such as the inability to fork or create a pipe.
Availability可用性: 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.
Availability可用性: Unix.
-
os.
EX_CANTCREAT
¶ Exit code that means a user specified output file could not be created.
Availability可用性: Unix.
-
os.
EX_IOERR
¶ Exit code that means that an error occurred while doing I/O on some file.
Availability可用性: 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.
Availability可用性: Unix.
-
os.
EX_PROTOCOL
¶ Exit code that means that a protocol exchange was illegal, invalid, or not understood.
Availability可用性: Unix.
-
os.
EX_NOPERM
¶ Exit code that means that there were insufficient permissions to perform the operation (but not intended for file system problems).
Availability可用性: Unix.
-
os.
EX_CONFIG
¶ Exit code that means that some kind of configuration error occurred.
Availability可用性: Unix.
-
os.
EX_NOTFOUND
¶ Exit code that means something like “an entry was not found”.
Availability可用性: Unix.
-
os.
fork
()¶ Fork a child process. Return
0
in the child and the child’s process id in the parent. If an error occursOSError
is raised.Note that some platforms including FreeBSD <= 6.3 and Cygwin have known issues when using
fork()
from a thread.Raises an auditing event
os.fork
with no arguments.Changed in version 3.8:版本3.8中更改: Callingfork()
in a subinterpreter is no longer supported (RuntimeError
is raised).Warning
See
ssl
for applications that use the SSL module with fork().Availability可用性: Unix.
-
os.
forkpty
()¶ Fork a child process, using a new pseudo-terminal as the child’s controlling terminal. Return a pair of
(pid, fd)
, where pid is0
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 thepty
module. If an error occursOSError
is raised.Raises an auditing event
os.forkpty
with no arguments.Changed in version 3.8:版本3.8中更改: Callingforkpty()
in a subinterpreter is no longer supported (RuntimeError
is raised).Availability可用性: some flavors of Unix.
-
os.
kill
(pid, sig)¶ -
Send signal sig to the process pid. Constants for the specific signals available 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 can only be sent to console processes which share a common console window, e.g., some subprocesses. Any other value for sig will cause the process to be unconditionally killed by the TerminateProcess API, and the exit code will be set to sig. The Windows version ofkill()
additionally takes process handles to be killed.See also
signal.pthread_kill()
.Raises an auditing event
os.kill
with argumentspid
,sig
.New in version 3.2.版本3.2中新增。Windows support.
-
os.
killpg
(pgid, sig)¶ -
Send the signal sig to the process group pgid.
Raises an auditing event
os.killpg
with argumentspgid
,sig
.Availability可用性: Unix.
-
os.
nice
(increment)¶ Add increment to the process’s “niceness”. Return the new niceness.
Availability可用性: Unix.
-
os.
pidfd_open
(pid, flags=0)¶ Return a file descriptor referring to the process pid. This descriptor can be used to perform process management without races and signals. The flags argument is provided for future extensions; no flag values are currently defined.
See the pidfd_open(2) man page for more details.
Availability可用性: Linux 5.3+New in version 3.9.版本3.9中新增。
-
os.
plock
(op)¶ Lock program segments into memory. The value of op (defined in
<sys/lock.h>
) determines which segments are locked.Availability可用性: Unix.
-
os.
popen
(cmd, mode='r', buffering=- 1)¶ Open a pipe to or from command cmd. The return value is an open file object connected 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 as the corresponding argument to the built-inopen()
function. The returned file object reads or writes text strings rather than bytes.The
close
method returnsNone
if the subprocess exited successfully, or the subprocess’s return code if there was an error. On POSIX systems, if the return code is positive it represents the return value of the process left-shifted by one byte. If the return code is negative, the process was terminated by the signal given by the negated value of the return code. (For example, the return value might be- signal.SIGKILL
if the subprocess was killed.) On Windows systems, the return value contains the signed integer return code from the child process.On Unix,
waitstatus_to_exitcode()
can be used to convert theclose
method result (exit status) into an exit code if it is notNone
. On Windows, theclose
method result is directly the exit code (orNone
).This is implemented using
subprocess.Popen
; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.
-
os.
posix_spawn
(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 ofposix_spawn()
.The positional-only arguments path, args, and env are similar to
execve()
.The path parameter is the path to the executable file. The path should contain a directory. Use
posix_spawnp()
to pass an executable file without directory.The file_actions argument may be a sequence of tuples describing actions to take on specific file descriptors in the child process between the C library implementation’s
fork()
andexec()
steps. The first item in each tuple must be one of the three type indicator listed below describing the remaining tuple elements:-
os.
POSIX_SPAWN_OPEN
¶ (
os.POSIX_SPAWN_OPEN
, fd, path, flags, mode)Performs
os.dup2(os.open(path, flags, mode), fd)
.
-
os.
POSIX_SPAWN_CLOSE
¶ (
os.POSIX_SPAWN_CLOSE
, fd)Performs
os.close(fd)
.
-
os.
POSIX_SPAWN_DUP2
¶ (
os.POSIX_SPAWN_DUP2
, fd, new_fd)Performs
os.dup2(fd, new_fd)
.
These tuples correspond to the C library
posix_spawn_file_actions_addopen()
,posix_spawn_file_actions_addclose()
, andposix_spawn_file_actions_adddup2()
API calls used to prepare for theposix_spawn()
call itself.The setpgroup argument will set the process group of the child to the value specified. If the value specified is 0, the child’s process group ID will be made the same as its process ID. If the value of setpgroup is not set, the child will inherit the parent’s process group ID. This argument corresponds to the C library
POSIX_SPAWN_SETPGROUP
flag.If the resetids argument is
True
it will reset the effective UID and GID of the child to the real UID and GID of the parent process. If the argument isFalse
, then the child retains the effective UID and GID of the parent. In either case, if the set-user-ID and set-group-ID permission bits are enabled on the executable file, their effect will override the setting of the effective UID and GID. This argument corresponds to the C libraryPOSIX_SPAWN_RESETIDS
flag.If the setsid argument is
True
, it will create a new session ID for posix_spawn. setsid requiresPOSIX_SPAWN_SETSID
orPOSIX_SPAWN_SETSID_NP
flag. Otherwise,NotImplementedError
is raised.The setsigmask argument will set the signal mask to the signal set specified. If the parameter is not used, then the child inherits the parent’s signal mask. This argument corresponds to the C library
POSIX_SPAWN_SETSIGMASK
flag.The sigdef argument will reset the disposition of all signals in the set specified. This argument corresponds to the C library
POSIX_SPAWN_SETSIGDEF
flag.The scheduler argument must be a tuple containing the (optional) scheduler policy and an instance of
sched_param
with the scheduler parameters. A value ofNone
in the place of the scheduler policy indicates that is not being provided. This argument is a combination of the C libraryPOSIX_SPAWN_SETSCHEDPARAM
andPOSIX_SPAWN_SETSCHEDULER
flags.Raises an auditing event
os.posix_spawn
with argumentspath
,argv
,env
.New in version 3.8.版本3.8中新增。Availability可用性: Unix.-
-
os.
posix_spawnp
(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 searches for the executable file in the list of directories specified by thePATH
environment variable (in the same way as forexecvp(3)
).Raises an auditing event
os.posix_spawn
with argumentspath
,argv
,env
.New in version 3.8.版本3.8中新增。Availability可用性: Seeposix_spawn()
documentation.
-
os.
register_at_fork
(*, before=None, after_in_parent=None, after_in_child=None)¶ Register callables to be executed when a new child process is forked using
os.fork()
or similar process cloning APIs. The parameters are optional and keyword-only. Each specifies a different call point.before is a function called before forking a child process.
after_in_parent is a function called from the parent process after forking a child process.
after_in_child is a function called from the child process.
These calls are only made if control is expected to return to the Python interpreter. A typical
subprocess
launch will not trigger them as the child is not going to re-enter the interpreter.Functions registered for execution before forking are called in reverse registration order. Functions registered for execution after forking (either in the parent or in the child) are called in registration order.
Note that
fork()
calls made by third-party C code may not call those functions, unless it explicitly callsPyOS_BeforeFork()
,PyOS_AfterFork_Parent()
andPyOS_AfterFork_Child()
.There is no way to unregister a function.
Availability可用性: Unix.New in version 3.7.版本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 for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the Replacing Older Functions with the subprocess Module section.)If mode is
P_NOWAIT
, this function returns the process id of the new process; if mode isP_WAIT
, returns the process’s exit code if it exits normally, or-signal
, where signal is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with thewaitpid()
function.Note on VxWorks, this function doesn’t return
-signal
when the new process is killed. Instead it raises OSError exception.The “l” and “v” variants of the
spawn*
functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to thespawnl*()
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()
, andspawnvpe()
) will use thePATH
environment variable to locate the program file. When the environment is being replaced (using one of thespawn*e
variants, discussed in the next paragraph), the new environment is used as the source of thePATH
variable. The other variants,spawnl()
,spawnle()
,spawnv()
, andspawnve()
, will not use thePATH
variable to locate the executable; path must contain an appropriate absolute or relative path.For
spawnle()
,spawnlpe()
,spawnve()
, andspawnvpe()
(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 functionsspawnl()
,spawnlp()
,spawnv()
, andspawnvp()
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 of127
.As an example, the following calls to
spawnlp()
andspawnvpe()
are equivalent: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)Raises an auditing event
os.spawn
with argumentsmode
,path
,args
,env
.Availability可用性: Unix, Windows.spawnlp()
,spawnlpe()
,spawnvp()
andspawnvpe()
are not available on Windows.spawnle()
andspawnve()
are not thread-safe on Windows; we advise you to use thesubprocess
module instead.Changed in version 3.6:版本3.6中更改: Accepts a path-like object.
-
os.
P_NOWAIT
¶ -
os.
P_NOWAITO
¶ Possible values for the mode parameter to the
spawn*
family of functions. If either of these values is given, thespawn*()
functions will return as soon as the new process has been created, with the process id as the return value.Availability可用性: Unix, Windows.
-
os.
P_WAIT
¶ Possible value for the mode parameter to the
spawn*
family of functions. If this is given as mode, thespawn*()
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
if a signal kills the process.Availability可用性: Unix, Windows.
-
os.
P_DETACH
¶ -
os.
P_OVERLAY
¶ Possible values for the mode parameter to the
spawn*
family of functions. These are less portable than those listed above.P_DETACH
is similar toP_NOWAIT
, but the new process is detached from the console of the calling process. IfP_OVERLAY
is used, the current process will be replaced; thespawn*
function will not return.Availability可用性: Windows.
-
os.
startfile
(path[, operation][, arguments][, cwd][, show_cmd])¶ Start a file with its associated application.
When operation is not specified or
'open'
, this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.When another operation is given, it must be a “command verb” that specifies what 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).When launching an application, specify arguments to be passed as a single string. This argument may have no effect when using this function to launch a document.
The default working directory is inherited, but may be overridden by the cwd argument. This should be an absolute path. A relative path will be resolved against this argument.
Use show_cmd to override the default window style. Whether this has any effect will depend on the application being launched. Values are integers as supported by the Win32
ShellExecute()
function.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 retrieve the application’s exit status. The path parameter is relative to the current directory or cwd. If you want to use an absolute path, make sure the first character is not a slash ('/'
) Usepathlib
or theos.path.normpath()
function to ensure that paths are properly encoded for Win32.To reduce interpreter startup overhead, the Win32
ShellExecute()
function is not resolved until this function is first called. If the function cannot be resolved,NotImplementedError
will be raised.Raises an auditing event
os.startfile
with argumentspath
,operation
.Raises an auditing event
os.startfile/2
with argumentspath
,operation
,arguments
,cwd
,show_cmd
.Availability可用性: Windows.Changed in version 3.10:版本3.10中更改: Added the arguments, cwd and show_cmd arguments, and theos.startfile/2
audit event.
-
os.
system
(command)¶ Execute the command (a string) in a subshell. This is implemented by calling the Standard C function
system()
, and has the same limitations. Changes tosys.stdin
, etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.On Unix, the return value is the exit status of the process encoded in the format specified for
wait()
.On Windows, the return value is that returned by the system shell after running command. The shell is given by the Windows environment variable
COMSPEC
: it is usually cmd.exe, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation.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 Replacing Older Functions with the subprocess Module section in thesubprocess
documentation for some helpful recipes.On Unix,
waitstatus_to_exitcode()
can be used to convert the result (exit status) into an exit code. On Windows, the result is directly the exit code.Raises an auditing event
os.system
with argumentcommand
.Availability可用性: Unix, Windows.
-
os.
times
()¶ Returns the current global process times. The return value is an object with five attributes:
user
- user timesystem
- system timechildren_user
- user time of all child processeschildren_system
- system time of all child processeselapsed
- elapsed real time since a fixed point in the past
For backwards compatibility, this object also behaves like a five-tuple containing
user
,system
,children_user
,children_system
, andelapsed
in that order.See the Unix manual page times(2) and times(3) manual page on Unix or the GetProcessTimes MSDN on Windows. On Windows, only
user
andsystem
are known; the other attributes are zero.Availability可用性: Unix, Windows.Changed in version 3.3:版本3.3中更改:Return type changed from a tuple to a tuple-like object with named attributes.返回类型已从元组更改为具有命名属性的类似元组的对象。
-
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.等待子进程完成,并返回一个包含其pid和退出状态指示的元组:一个16位数字,其低位字节是终止进程的信号号,高位字节是退出状态(如果信号号为零);如果生成了核心文件,则设置低字节的高位。waitstatus_to_exitcode()
can be used to convert the exit status into an exit code.可用于将退出状态转换为退出代码。Availability可用性: Unix.See also
waitpid()
can be used to wait for the completion of a specific child process and has more options.可用于等待特定子进程的完成,并有更多选项。
-
os.
waitid
(idtype, id, options)¶ Wait for the completion of one or more child processes. idtype can be
P_PID
,P_PGID
,P_ALL
, orP_PIDFD
on Linux. id specifies the pid to wait on. options is constructed from the ORing of one or more ofWEXITED
,WSTOPPED
orWCONTINUED
and additionally may be ORed withWNOHANG
orWNOWAIT
. The return value is an object representing the data contained in thesiginfo_t
structure, namely:si_pid
,si_uid
,si_signo
,si_status
,si_code
orNone
ifWNOHANG
is specified and there are no children in a waitable state.Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
P_PID
¶ -
os.
P_PGID
¶ -
os.
P_ALL
¶ These are the possible values for idtype in
waitid()
. They affect how id is interpreted.Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
P_PIDFD
¶ This is a Linux-specific idtype that indicates that id is a file descriptor that refers to a process.这是一个Linux特定的idtype,指示id是引用进程的文件描述符。Availability可用性: Linux 5.4+New in version 3.9.版本3.9中新增。
-
os.
WEXITED
¶ -
os.
WSTOPPED
¶ -
os.
WNOWAIT
¶ Flags that can be used in options in
waitid()
that specify what child signal to wait for.Availability可用性: Unix.New in version 3.3.版本3.3中新增。
-
os.
CLD_EXITED
¶ -
os.
CLD_KILLED
¶ -
os.
CLD_DUMPED
¶ -
os.
CLD_TRAPPED
¶ -
os.
CLD_STOPPED
¶ -
os.
CLD_CONTINUED
¶ These are the possible values for
si_code
in the result returned bywaitid()
.Availability可用性: Unix.New in version 3.3.版本3.3中新增。Changed in version 3.9:版本3.9中更改: AddedCLD_KILLED
andCLD_STOPPED
values.
-
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, 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 options, which should be0
for normal operation.If pid is greater than
0
,waitpid()
requests status information for that specific process. If pid is0
, 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 is less than-1
, status is requested for any process in the process group-pid
(the absolute value of pid).An当系统调用返回-1时,将引发一个值为errno的OSError
is raised with the value of errno when the syscall returns -1.OSError
。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 options has no effect. pid can refer to any process whose id is known, not necessarily a child process. Thespawn*
functions called withP_NOWAIT
return suitable process handles.waitstatus_to_exitcode()
can be used to convert the exit status into an exit code.可用于将退出状态转换为退出代码。Changed in version 3.5:版本3.5中更改: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising anInterruptedError
exception (see PEP 475 for the rationale).
-
os.
wait3
(options)¶ Similar to
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 toresource
.getrusage()
for details on resource usage information. The option argument is the same as that provided towaitpid()
andwait4()
.waitstatus_to_exitcode()
can be used to convert the exit status into an exitcode.Availability可用性: Unix.
-
os.
wait4
(pid, options)¶ Similar to
waitpid()
, except a 3-element tuple, containing the child’s process id, exit status indication, and resource usage information is returned. Refer toresource
.getrusage()
for details on resource usage information. The arguments towait4()
are the same as those provided towaitpid()
.waitstatus_to_exitcode()
can be used to convert the exit status into an exitcode.可用于将退出状态转换为退出代码。Availability可用性: Unix.
-
os.
waitstatus_to_exitcode
(status)¶ Convert a wait status to an exit code.将等待状态转换为退出代码。On Unix:
If the process exited normally (if
WIFEXITED(status)
is true), return the process exit status (returnWEXITSTATUS(status)
): result greater than or equal to 0.If the process was terminated by a signal (if
WIFSIGNALED(status)
is true), return-signum
where signum is the number of the signal that caused the process to terminate (return-WTERMSIG(status)
): result less than 0.Otherwise, raise a
ValueError
.
On Windows, return status shifted right by 8 bits.
On Unix, if the process is being traced or if
waitpid()
was called withWUNTRACED
option, the caller must first check ifWIFSTOPPED(status)
is true. This function must not be called ifWIFSTOPPED(status)
is true.See also
WIFEXITED()
,WEXITSTATUS()
,WIFSIGNALED()
,WTERMSIG()
,WIFSTOPPED()
,WSTOPSIG()
functions.New in version 3.9.版本3.9中新增。
-
os.
WNOHANG
¶ The option for
waitpid()
to return immediately if no child process status is available immediately. The function returns(0, 0)
in this case.Availability可用性: 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.
Availability可用性: some Unix systems.
-
os.
WUNTRACED
¶ This option causes child processes to be reported if they have been stopped but their current state has not been reported since they were stopped.如果子进程已停止,但自停止后尚未报告其当前状态,则此选项会导致报告子进程。Availability可用性: Unix.
The following functions take a process status code as returned by system()
, wait()
, or waitpid()
as a parameter. They may be used to determine the disposition of a process.它们可用于确定流程的处置。
-
os.
WCOREDUMP
(status)¶ Return
True
if a core dump was generated for the process, otherwise returnFalse
.This function should be employed only if
WIFSIGNALED()
is true.Availability可用性: Unix.
-
os.
WIFCONTINUED
(status)¶ Return
True
if a stopped child has been resumed by delivery ofSIGCONT
(if the process has been continued from a job control stop), otherwise returnFalse
.See
WCONTINUED
option.Availability可用性: Unix.
-
os.
WIFSTOPPED
(status)¶ Return
True
if the process was stopped by delivery of a signal, otherwise returnFalse
.WIFSTOPPED()
only returnsTrue
if thewaitpid()
call was done usingWUNTRACED
option or when the process is being traced (see ptrace(2)).Availability可用性: Unix.
-
os.
WIFSIGNALED
(status)¶ Return
True
if the process was terminated by a signal, otherwise returnFalse
.Availability可用性: Unix.
-
os.
WIFEXITED
(status)¶ Return
True
if the process exited terminated normally, that is, by callingexit()
or_exit()
, or by returning frommain()
; otherwise returnFalse
.Availability可用性: Unix.
-
os.
WEXITSTATUS
(status)¶ Return the process exit status.
This function should be employed only if
WIFEXITED()
is true.Availability可用性: Unix.
-
os.
WSTOPSIG
(status)¶ Return the signal which caused the process to stop.返回导致进程停止的信号。This function should be employed only if
WIFSTOPPED()
is true.Availability可用性: Unix.
-
os.
WTERMSIG
(status)¶ Return the number of the signal that caused the process to terminate.返回导致进程终止的信号的编号。This function should be employed only if仅当WIFSIGNALED()
is true.WIFSIGNALED()
为true
时,才应使用此函数。Availability可用性: Unix.
Interface to the scheduler调度程序接口¶
These functions control how a process is allocated CPU time by the operating system. 这些函数控制操作系统如何分配进程的CPU时间。They are only available on some Unix platforms. 它们仅在某些Unix平台上可用。For more detailed information, consult your Unix manpages.有关更多详细信息,请参阅Unix手册页。
New in version 3.3.版本3.3中新增。
The following scheduling policies are exposed if they are supported by the operating system.如果操作系统支持以下调度策略,则会公开这些策略。
-
os.
SCHED_OTHER
¶ The default scheduling policy.默认计划策略。
-
os.
SCHED_BATCH
¶ Scheduling policy for CPU-intensive processes that tries to preserve interactivity on the rest of the computer.CPU密集型进程的调度策略,该策略试图保持计算机其余部分的交互性。
-
os.
SCHED_IDLE
¶ Scheduling policy for extremely low priority background tasks.极低优先级后台任务的调度策略。
-
os.
SCHED_SPORADIC
¶ Scheduling policy for sporadic server programs.零星服务器程序的调度策略。
-
os.
SCHED_FIFO
¶ A First In First Out scheduling policy.先进先出计划策略。
-
os.
SCHED_RR
¶ A round-robin scheduling policy.循环调度策略。
-
os.
SCHED_RESET_ON_FORK
¶ This flag can be OR’ed with any other scheduling policy.此标志可以与任何其他调度策略一起使用或。When a process with this flag set forks, its child’s scheduling policy and priority are reset to the default.当设置了此标志的进程分叉时,其子进程的调度策略和优先级将重置为默认值。
-
class
os.
sched_param
(sched_priority)¶ This class represents tunable scheduling parameters used in
sched_setparam()
,sched_setscheduler()
, andsched_getparam()
. It is immutable.At the moment, there is only one possible parameter:目前,只有一个可能的参数:-
sched_priority
¶ The scheduling priority for a scheduling policy.调度策略的调度优先级。
-
-
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. A pid of 0 means the calling process. policy is one of the scheduling policy constants above. param is a
sched_param
instance.
-
os.
sched_getscheduler
(pid)¶ Return the scheduling policy for the process with PID pid. A pid of 0 means the calling process. The result is one of the scheduling policy constants above.
-
os.
sched_setparam
(pid, param)¶ Set the scheduling parameters for the process with PID pid. A pid of 0 means the calling process. param is a
sched_param
instance.
-
os.
sched_getparam
(pid)¶ Return the scheduling parameters as a
sched_param
instance for the process with PID pid. A 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. A pid of 0 means the calling process.
-
os.
sched_yield
()¶ Voluntarily relinquish the CPU.
-
os.
sched_setaffinity
(pid, mask)¶ Restrict the process with PID pid (or the current process if zero) to a set of CPUs.将具有PID pid(或当前进程,如果为零)的进程限制为一组CPU。maskis an iterable of integers representing the set of CPUs to which the process should be restricted.是一个整数的iterable,表示进程应限制到的CPU集。
-
os.
sched_getaffinity
(pid)¶ Return the set of CPUs the process with PID pid (or the current process if zero) is restricted to.
Miscellaneous System Information其他系统信息¶
-
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传递整数。If the configuration value specified by name isn’t defined,
None
is returned.If name is a string and is not known,
ValueError
is raised. If a specific value for name is not supported by the host system, even if it is included inconfstr_names
, anOSError
is raised witherrno.EINVAL
for the error number.Availability可用性: Unix.
-
os.
confstr_names
¶ Dictionary mapping names accepted by
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.这可用于确定系统已知的名称集。Availability可用性: Unix.
-
os.
cpu_count
()¶ Return the number of CPUs in the system. Returns
None
if undetermined.This number is not equivalent to the number of CPUs the current process can use.此数字不等于当前进程可以使用的CPU数量。The number of usable CPUs can be obtained withlen(os.sched_getaffinity(0))
New in version 3.4.版本3.4中新增。
-
os.
getloadavg
()¶ Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises
OSError
if the load average was unobtainable.Availability可用性: Unix.
-
os.
sysconf
(name)¶ Return integer-valued system configuration values. If the configuration value specified by name isn’t defined,
-1
is returned. The comments regarding the name parameter forconfstr()
apply here as well; the dictionary that provides information on the known names is given bysysconf_names
.Availability可用性: Unix.
-
os.
sysconf_names
¶ Dictionary mapping names accepted by
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.Availability可用性: Unix.
The following data values are used to support path manipulation operations. These are 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 current directory. This is
'.'
for Windows and POSIX. Also available viaos.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 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 this is not sufficient to be able to parse or concatenate pathnames — useos.path.split()
andos.path.join()
— but it is occasionally useful. Also available viaos.path
.
-
os.
altsep
¶ An alternative character used by the operating system to separate pathname components, or
None
if only one separator character exists. This is set to'/'
on Windows systems wheresep
is a backslash. Also available viaos.path
.
-
os.
extsep
¶ The character which separates the base filename from the extension; for example, the
'.'
inos.py
. Also available viaos.path
.
-
os.
pathsep
¶ The character conventionally used by the operating system to separate search path components (as in
PATH
), such as':'
for POSIX or';'
for Windows. Also available viaos.path
.
-
os.
defpath
¶ The default search path used by
exec*p*
andspawn*p*
if the environment doesn’t have a'PATH'
key. Also available viaos.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'
instead, on all platforms.
-
os.
devnull
¶ The file path of the null device. For example:
'/dev/null'
for POSIX,'nul'
for Windows. Also available viaos.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 page dlopen(3) for what the different flags mean.New in version 3.3.版本3.3中新增。
Random numbers随机数¶
-
os.
getrandom
(size, flags=0)¶ Get up to size random bytes. The function can return less bytes than requested.
These bytes can be used to seed user-space random number generators or for cryptographic purposes.
getrandom()
relies on entropy gathered from device drivers and other sources of environmental noise. Unnecessarily reading large quantities of data will have a negative impact on other users of the/dev/random
and/dev/urandom
devices.The flags argument is a bit mask that can contain zero or more of the following values ORed together:
os.GRND_RANDOM
andGRND_NONBLOCK
.See also the Linux getrandom() manual page.
Availability可用性: Linux 3.17 and newer.New in version 3.6.版本3.6中新增。
-
os.
urandom
(size)¶ Return a bytestring of size random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.
On Linux, if the
getrandom()
syscall is available, it is used in blocking mode: block until the system urandom entropy pool is initialized (128 bits of entropy are collected by the kernel). See the PEP 524 for the rationale. On Linux, thegetrandom()
function can be used to get random bytes in non-blocking mode (using theGRND_NONBLOCK
flag) or to poll until the system urandom entropy pool is initialized.On a Unix-like system, random bytes are read from the
/dev/urandom
device. If the/dev/urandom
device is not available or not readable, theNotImplementedError
exception is raised.On Windows, it will use
CryptGenRandom()
.See also
The
secrets
module provides higher level functions. For an easy-to-use interface to the random number generator provided by your platform, please seerandom.SystemRandom
.Changed in version 3.6.0:版本3.6.0中更改:On Linux,在Linux上,getrandom()
is now used in blocking mode to increase the security.getrandom()
现在用于阻塞模式以提高安全性。Changed in version 3.5.2:版本3.5.2中更改:On Linux, if the在Linux上,如果getrandom()
syscall blocks (the urandom entropy pool is not initialized yet), fall back on reading/dev/urandom
.getrandom()
系统调用被阻塞(urandom熵池尚未初始化),请回过头来读取/dev/urandom
。Changed in version 3.5:版本3.5中更改: On Linux 3.17 and newer, thegetrandom()
syscall is now used when available. On OpenBSD 5.6 and newer, the Cgetentropy()
function is now used. These functions avoid the usage of an internal file descriptor.
-
os.
GRND_NONBLOCK
¶ By default, when reading from
/dev/random
,getrandom()
blocks if no random bytes are available, and when reading from/dev/urandom
, it blocks if the entropy pool has not yet been initialized.If the
GRND_NONBLOCK
flag is set, thengetrandom()
does not block in these cases, but instead immediately raisesBlockingIOError
.New in version 3.6.版本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.New in version 3.6.版本3.6中新增。