15.1. os
— 操作系统接口模块¶
该模块提供了一些方便使用操作系统相关功能的函数。 如果你是想读写一个文件,请参阅 open()
,如果你想操作路径,请参阅 os.path
模块,如果你想在命令行上读取所有文件中的所有行请参阅 fileinput
模块。 有关创建临时文件和目录的方法,请参阅 tempfile
模块,对于高级文件目录处理,请参阅 shutil
模块。
关于这些函数的可用性的说明:
- 所有 Python 内建的操作系统相关的模块的设计都是为了使得在同一功能可用的情况下,保持接口的一致性;例如,函数
os.stat(path)
以相同的格式返回关于 path 的统计信息(这个函数同时也是起源于 POSIX 接口)。 - 针对特定的操作的拓展同样在可用于
os
模块,但是使用它们必然会对可移植性产生威胁。 - An “Availability: Unix” note means that this function is commonly found on Unix systems. It does not make any claims about its existence on a specific operating system.
- If not separately noted, all functions that claim “Availability: Unix” are supported on Mac OS X, which builds on a Unix core.
注解
此模块的所有函数在遇到不可用或不可访问的文件名或路径,以及其他类型正确,但不被操作系统接受的参数时,会引发 OSError
异常。
-
os.
name
¶ The name of the operating system dependent module imported. The following names have currently been registered:
'posix'
,'nt'
,'os2'
,'ce'
,'java'
,'riscos'
.
15.1.1. 进程参数¶
这些函数和数据项提供了操作当前进程和用户的信息。
-
os.
environ
¶ 一个表示字符串环境的 mapping 对象。 例如,
environ['HOME']
是你的主目录(在某些平台上)的路径名,相当于 C 中的getenv("HOME")
。这个映射是在第一次导入
os
模块时捕获的,通常作为 Python 启动时处理site.py
的一部分。除了通过直接修改os.environ
之外,在此之后对环境所做的更改不会反映在os.environ
中。如果平台支持
putenv()
函数,这个映射除了可以用于查询环境外还能用于修改环境。 当这个映射被修改时,putenv()
将被自动调用。注解
直接调用
putenv()
并不会影响os.environ
,所以推荐直接修改``os.environ``。注解
在某些平台上,包括 FreeBSD 和 Mac OS X,设置
environ
可能导致内存泄露。参阅putenv()
的系统文档。如果平台没有提供
putenv()
, 为了使启动的子进程使用修改后的环境,一份修改后的映射会被传给合适的进程创建函数。如果平台支持
unsetenv()
函数,你可以通过删除映射中元素的方式来删除对应的环境变量。当一个元素被从os.environ
删除时,以及pop()
或clear()
被调用时,unsetenv()
会被自动调用。在 2.6 版更改: Also unset environment variables when calling
os.environ.clear()
andos.environ.pop()
.
-
os.
chdir
(path) -
os.
fchdir
(fd) -
os.
getcwd
() 以上函数请参阅 Files and Directories 。
-
os.
ctermid
()¶ 返回与进程控制终端对应的文件名。
Availability: Unix.
-
os.
getegid
()¶ 返回当前进程的有效组ID。对应当前进程执行文件的 “set id” 位。
Availability: Unix.
-
os.
geteuid
()¶ 返回当前进程的有效用户ID。
Availability: Unix.
-
os.
getgid
()¶ 返回当前进程的实际组ID。
Availability: Unix.
-
os.
getgroups
()¶ 返回当前进程对应的组ID列表
Availability: Unix.
注解
在Mac OS X系统中,
getgroups()
会和其他 Unix 平台有些不同。如果 Python 解释器是在10.5
或更早版本中部署,getgroups()
返回当前用户进程相关的有效组ID列表。 该列表长度由于系统预设的接口限制,最长为 16。 而且在适当的权限下,返回结果还会因getgroups()
而发生变化;如果 Python 解释器是在10.5
以上版本中部署,getgroups()
返回进程所属有效用户 ID 所对应的用户的组 ID 列表,组用户列表可能因为进程的生存周期而发生变动,而且也不会因为setgroups()
的调用而发生,返回的组用户列表长度也没有长度 16 的限制。在部署中,Python 解释器用到的变量MACOSX_DEPLOYMENT_TARGET
可以用sysconfig.get_config_var()
。
-
os.
initgroups
(username, gid)¶ 调用系统 initgroups(),使用指定用户所在的所有值来初始化组访问列表,包括指定的组ID。
Availability: Unix.
2.7 新版功能.
-
os.
getlogin
()¶ Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use the environment variable
LOGNAME
to find out who the user is, orpwd.getpwuid(os.getuid())[0]
to get the login name of the process’s real user id.Availability: Unix.
-
os.
getpgid
(pid)¶ 根据进程id pid 返回进程的组 ID 列表。如果 pid 为 0,则返回当前进程的进程组 ID 列表
Availability: Unix.
2.3 新版功能.
-
os.
getpgrp
()¶ 返回当时进程组的ID
Availability: Unix.
-
os.
getpid
()¶ 返回当前进程ID
Availability: Unix, Windows.
-
os.
getppid
()¶ Return the parent’s process id.
Availability: Unix.
-
os.
getresuid
()¶ 返回一个由 (ruid, euid, suid) 所组成的元组,分别表示当前进程的真实用户ID,有效用户ID和甲暂存用户ID。
Availability: Unix.
2.7 新版功能.
-
os.
getresgid
()¶ 返回一个由 (rgid, egid, sgid) 所组成的元组,分别表示当前进程的真实组ID,有效组ID和暂存组ID。
Availability: Unix.
2.7 新版功能.
-
os.
getuid
()¶ 返回当前进程的真实用户ID。
Availability: Unix.
-
os.
getenv
(varname[, value])¶ Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to
None
.Availability: most flavors of Unix, Windows.
-
os.
putenv
(varname, value)¶ Set the environment variable named varname to the string value. Such changes to the environment affect subprocesses started with
os.system()
,popen()
orfork()
andexecv()
.Availability: most flavors of Unix, Windows.
注解
在一些平台,包括 FreeBSD 和 Mac OS X,设置
environ
可能导致内存泄露。详情参考 putenv 相关系统文档。当系统支持
putenv()
时,os.environ
中的参数赋值会自动转换为对putenv()
的调用。不过putenv()
的调用不会更新os.environ
,因此最好使用os.environ
对变量赋值。
-
os.
setegid
(egid)¶ 设置当前进程的有效组ID。
Availability: Unix.
-
os.
seteuid
(euid)¶ 设置当前进程的有效用户ID。
Availability: Unix.
-
os.
setgid
(gid)¶ 设置当前进程的组ID。
Availability: Unix.
-
os.
setgroups
(groups)¶ 将 group 参数值设置为与当进程相关联的附加组ID列表。group 参数必须为一个序列,每个元素应为每个组的数字ID。该操作通常只适用于超级用户。
Availability: Unix.
2.2 新版功能.
注解
在 Mac OS X 中,groups 的长度不能超过系统定义的最大有效组 ID 个数,一般为 16。 如果它没有返回与调用 setgroups() 所设置的相同的组列表,请参阅
getgroups()
的文档。
-
os.
setpgrp
()¶ 根据已实现的版本(如果有)来调用系统
setpgrp()
或setpgrp(0, 0)
。相关说明,请参考 Unix 手册。Availability: Unix.
-
os.
setpgid
(pid, pgrp)¶ 使用系统调用
setpgid()
,将 pid 对应进程的组ID设置为 pgrp。相关说明,请参考 Unix 手册。Availability: Unix.
-
os.
setregid
(rgid, egid)¶ 设置当前进程的真实和有效组ID。
Availability: Unix.
-
os.
setresgid
(rgid, egid, sgid)¶ 设置当前进程的真实,有效和暂存组ID。
Availability: Unix.
2.7 新版功能.
-
os.
setresuid
(ruid, euid, suid)¶ 设置当前进程的真实,有效和暂存用户ID。
Availability: Unix.
2.7 新版功能.
-
os.
setreuid
(ruid, euid)¶ 设置当前进程的真实和有效用户ID。
Availability: Unix.
-
os.
getsid
(pid)¶ 调用系统调用
getsid()
。 相关语义请参阅 Unix 手册。Availability: Unix.
2.4 新版功能.
-
os.
setsid
()¶ 使用系统调用
getsid()
。相关说明,请参考 Unix 手册。Availability: Unix.
-
os.
setuid
(uid)¶ 设置当前进程的用户ID。
Availability: Unix.
-
os.
strerror
(code)¶ 根据 code 中的错误码返回错误消息。 在某些平台上当给出未知错误码时
strerror()
将返回NULL
并会引发ValueError
。Availability: Unix, Windows.
-
os.
umask
(mask)¶ 设定当前数值掩码并返回之前的掩码。
Availability: Unix, Windows.
-
os.
uname
()¶ Return a 5-tuple containing information identifying the current operating system. The tuple contains 5 strings:
(sysname, nodename, release, version, machine)
. Some systems truncate the nodename to 8 characters or to the leading component; a better way to get the hostname issocket.gethostname()
or evensocket.gethostbyaddr(socket.gethostname())
.Availability: recent flavors of Unix.
-
os.
unsetenv
(varname)¶ Unset (delete) the environment variable named varname. Such changes to the environment affect subprocesses started with
os.system()
,popen()
orfork()
andexecv()
.当系统支持
unsetenv()
,删除在os.environ
中的变量会自动转换为对unsetenv()
的调用。但是unsetenv()
不能更新os.environ
,因此最好直接删除os.environ
中的变量。Availability: most flavors of Unix, Windows.
15.1.2. 创建文件对象¶
These functions create new file objects. (See also open()
.)
-
os.
fdopen
(fd[, mode[, bufsize]])¶ Return an open file object connected to the file descriptor fd. The mode and bufsize arguments have the same meaning as the corresponding arguments to the built-in
open()
function. Iffdopen()
raises an exception, it leaves fd untouched (unclosed).Availability: Unix, Windows.
在 2.3 版更改: When specified, the mode argument must now start with one of the letters
'r'
,'w'
, or'a'
, otherwise aValueError
is raised.在 2.5 版更改: On Unix, when the mode argument starts with
'a'
, the O_APPEND flag is set on the file descriptor (which thefdopen()
implementation already does on most platforms).
-
os.
popen
(command[, mode[, bufsize]])¶ Open a pipe to or from command. 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 bufsize argument has the same meaning as the corresponding argument to the built-inopen()
function. The exit status of the command (encoded in the format specified forwait()
) is available as the return value of theclose()
method of the file object, except that when the exit status is zero (termination without errors),None
is returned.Availability: Unix, Windows.
2.6 版后已移除: This function is obsolete. Use the
subprocess
module. Check especially the Replacing Older Functions with the subprocess Module section.在 2.0 版更改: This function worked unreliably under Windows in earlier versions of Python. This was due to the use of the
_popen()
function from the libraries provided with Windows. Newer versions of Python do not use the broken implementation from the Windows libraries.
-
os.
tmpfile
()¶ Return a new file object opened in update mode (
w+b
). The file has no directory entries associated with it and will be automatically deleted once there are no file descriptors for the file.Availability: Unix, Windows.
There are a number of different popen*()
functions that provide slightly
different ways to create subprocesses.
2.6 版后已移除: All of the popen*()
functions are obsolete. Use the subprocess
module.
For each of the popen*()
variants, if bufsize is specified, it
specifies the buffer size for the I/O pipes. mode, if provided, should be the
string 'b'
or 't'
; on Windows this is needed to determine whether the
file objects should be opened in binary or text mode. The default value for
mode is 't'
.
Also, for each of these variants, on Unix, cmd may be a sequence, in which
case arguments will be passed directly to the program without shell intervention
(as with os.spawnv()
). If cmd is a string it will be passed to the shell
(as with os.system()
).
These methods do not make it possible to retrieve the exit status from the child
processes. The only way to control the input and output streams and also
retrieve the return codes is to use the subprocess
module; these are only
available on Unix.
For a discussion of possible deadlock conditions related to the use of these functions, see Flow Control Issues.
-
os.
popen2
(cmd[, mode[, bufsize]])¶ Execute cmd as a sub-process and return the file objects
(child_stdin, child_stdout)
.2.6 版后已移除: This function is obsolete. Use the
subprocess
module. Check especially the Replacing Older Functions with the subprocess Module section.Availability: Unix, Windows.
2.0 新版功能.
-
os.
popen3
(cmd[, mode[, bufsize]])¶ Execute cmd as a sub-process and return the file objects
(child_stdin, child_stdout, child_stderr)
.2.6 版后已移除: This function is obsolete. Use the
subprocess
module. Check especially the Replacing Older Functions with the subprocess Module section.Availability: Unix, Windows.
2.0 新版功能.
-
os.
popen4
(cmd[, mode[, bufsize]])¶ Execute cmd as a sub-process and return the file objects
(child_stdin, child_stdout_and_stderr)
.2.6 版后已移除: This function is obsolete. Use the
subprocess
module. Check especially the Replacing Older Functions with the subprocess Module section.Availability: Unix, Windows.
2.0 新版功能.
(Note that child_stdin, child_stdout, and child_stderr
are named from the
point of view of the child process, so child_stdin is the child’s standard
input.)
This functionality is also available in the popen2
module using functions
of the same names, but the return values of those functions have a different
order.
15.1.3. 文件描述符操作¶
这些函数对文件描述符所引用的 I/O 流进行操作。
文件描述符是一些小的整数,对应于当前进程所打开的文件。例如,标准输入的文件描述符通常是0,标准输出是1,标准错误是2。之后被进程打开的文件的文件描述符会被依次指定为3,4,5等。“文件描述符”这个词有点误导性,在 Unix 平台中套接字和管道也被文件描述符所引用。
The fileno()
method can be used to obtain the file descriptor
associated with a file object when required. Note that using the file
descriptor directly will bypass the file object methods, ignoring aspects such
as internal buffering of data.
-
os.
close
(fd)¶ 关闭文件描述符 fd。
Availability: Unix, Windows.
-
os.
closerange
(fd_low, fd_high)¶ Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. Equivalent to:
for fd in xrange(fd_low, fd_high): try: os.close(fd) except OSError: pass
Availability: Unix, Windows.
2.6 新版功能.
-
os.
dup
(fd)¶ Return a duplicate of file descriptor fd.
Availability: Unix, Windows.
-
os.
dup2
(fd, fd2)¶ Duplicate file descriptor fd to fd2, closing the latter first if necessary.
Availability: Unix, Windows.
-
os.
fchmod
(fd, mode)¶ Change the mode of the file given by fd to the numeric mode. See the docs for
chmod()
for possible values of mode.Availability: Unix.
2.6 新版功能.
-
os.
fchown
(fd, uid, gid)¶ Change the owner and group id of the file given by fd to the numeric uid and gid. To leave one of the ids unchanged, set it to -1.
Availability: Unix.
2.6 新版功能.
-
os.
fdatasync
(fd)¶ 强制将文件描述符 fd 指定文件写入磁盘。不强制更新元数据。
Availability: Unix.
注解
该功能在 MacOS 中不可用。
-
os.
fpathconf
(fd, name)¶ Return system configuration information relevant to an open 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.Availability: Unix.
-
os.
fstatvfs
(fd)¶ Return information about the filesystem containing the file associated with file descriptor fd, like
statvfs()
.Availability: Unix.
-
os.
fsync
(fd)¶ Force write of file with filedescriptor fd to disk. On Unix, this calls the native
fsync()
function; on Windows, the MS_commit()
function.If you’re starting with a Python file object f, first do
f.flush()
, and then doos.fsync(f.fileno())
, to ensure that all internal buffers associated with f are written to disk.Availability: Unix, and Windows starting in 2.2.3.
-
os.
ftruncate
(fd, length)¶ Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size.
Availability: Unix.
-
os.
isatty
(fd)¶ Return
True
if the file descriptor fd is open and connected to a tty(-like) device, elseFalse
.
-
os.
lseek
(fd, pos, how)¶ Set the current position of file descriptor fd to position pos, modified by 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. Return the new cursor position in bytes, starting from the beginning.Availability: Unix, Windows.
-
os.
SEEK_SET
¶ -
os.
SEEK_CUR
¶ -
os.
SEEK_END
¶ Parameters to the
lseek()
function. Their values are 0, 1, and 2, respectively.Availability: Windows, Unix.
2.5 新版功能.
-
os.
open
(file, flags[, mode])¶ Open the file file and set various flags according to flags and possibly its mode according to mode. The default mode is
0777
(octal), and the current umask value is first masked out. Return the file descriptor for the newly opened file.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 this module too (see open() flag constants). In particular, on Windows addingO_BINARY
is needed to open files in binary mode.Availability: Unix, Windows.
-
os.
openpty
()¶ Open a new pseudo-terminal pair. Return a pair of file descriptors
(master, slave)
for the pty and the tty, respectively. For a (slightly) more portable approach, use thepty
module.Availability: some flavors of Unix.
-
os.
pipe
()¶ Create a pipe. Return a pair of file descriptors
(r, w)
usable for reading and writing, respectively.Availability: Unix, Windows.
-
os.
read
(fd, n)¶ Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned.
Availability: Unix, Windows.
-
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 string str to file descriptor fd. Return the number of bytes actually written.
Availability: Unix, Windows.
注解
This function is intended for low-level I/O and must be applied to a file descriptor as returned by
os.open()
orpipe()
. To write a “file object” returned by the built-in functionopen()
or bypopen()
orfdopen()
, orsys.stdout
orsys.stderr
, use itswrite()
method.
15.1.3.1. open()
flag constants¶
The following constants are options for the flags parameter to the
open()
function. They can be combined using the bitwise OR operator
|
. 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.
15.1.4. Files and Directories¶
-
os.
access
(path, mode)¶ 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.Availability: Unix, Windows.
注解
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 IOError as e: if e.errno == errno.EACCES: return "some default data" # Not a permission error. raise else: with fp: return fp.read()
注解
I/O operations may fail even when
access()
indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.
-
os.
chdir
(path)¶ Change the current working directory to path.
Availability: Unix, Windows.
-
os.
fchdir
(fd)¶ Change the current working directory to the directory represented by the file descriptor fd. The descriptor must refer to an opened directory, not an open file.
Availability: Unix.
2.3 新版功能.
-
os.
getcwd
()¶ Return a string representing the current working directory.
Availability: Unix, Windows.
-
os.
getcwdu
()¶ Return a Unicode object representing the current working directory.
Availability: Unix, Windows.
2.3 新版功能.
-
os.
chflags
(path, flags)¶ Set the flags of path to the numeric flags. flags may take a combination (bitwise OR) of the following values (as defined in the
stat
module):stat.UF_NODUMP
stat.UF_IMMUTABLE
stat.UF_APPEND
stat.UF_OPAQUE
stat.UF_NOUNLINK
stat.UF_COMPRESSED
stat.UF_HIDDEN
stat.SF_ARCHIVED
stat.SF_IMMUTABLE
stat.SF_APPEND
stat.SF_NOUNLINK
stat.SF_SNAPSHOT
Availability: Unix.
2.6 新版功能.
-
os.
chroot
(path)¶ Change the root directory of the current process to path. Availability: Unix.
2.2 新版功能.
-
os.
chmod
(path, mode)¶ 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:stat.S_ISUID
stat.S_ISGID
stat.S_ENFMT
stat.S_ISVTX
stat.S_IREAD
stat.S_IWRITE
stat.S_IEXEC
stat.S_IRWXU
stat.S_IRUSR
stat.S_IWUSR
stat.S_IXUSR
stat.S_IRWXG
stat.S_IRGRP
stat.S_IWGRP
stat.S_IXGRP
stat.S_IRWXO
stat.S_IROTH
stat.S_IWOTH
stat.S_IXOTH
Availability: Unix, Windows.
注解
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.
-
os.
chown
(path, uid, gid)¶ 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.
Availability: Unix.
-
os.
lchflags
(path, flags)¶ Set the flags of path to the numeric flags, like
chflags()
, but do not follow symbolic links.Availability: Unix.
2.6 新版功能.
-
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.Availability: Unix.
2.6 新版功能.
-
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.
Availability: Unix.
2.3 新版功能.
-
os.
link
(source, link_name)¶ Create a hard link pointing to source named link_name.
Availability: Unix.
-
os.
listdir
(path)¶ Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries
'.'
and'..'
even if they are present in the directory.Availability: Unix, Windows.
在 2.3 版更改: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects. Undecodable filenames will still be returned as string objects.
-
os.
lstat
(path)¶ Perform the equivalent of an
lstat()
system call on the given path. Similar tostat()
, but does not follow symbolic links. On platforms that do not support symbolic links, this is an alias forstat()
.
-
os.
mkfifo
(path[, mode])¶ Create a FIFO (a named pipe) named path with numeric mode mode. The default mode is
0666
(octal). The current umask value is first masked out from the mode.Availability: Unix.
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.
-
os.
mknod
(filename[, mode=0600[, device=0]])¶ Create a filesystem node (file, device special file or named pipe) named filename. 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.2.3 新版功能.
-
os.
major
(device)¶ Extract the device major number from a raw device number (usually the
st_dev
orst_rdev
field fromstat
).2.3 新版功能.
-
os.
minor
(device)¶ Extract the device minor number from a raw device number (usually the
st_dev
orst_rdev
field fromstat
).2.3 新版功能.
-
os.
makedev
(major, minor)¶ Compose a raw device number from the major and minor device numbers.
2.3 新版功能.
-
os.
mkdir
(path[, mode])¶ Create a directory named path with numeric mode mode. The default mode is
0777
(octal). If the directory already exists,OSError
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.It is also possible to create temporary directories; see the
tempfile
module’stempfile.mkdtemp()
function.Availability: Unix, Windows.
-
os.
makedirs
(path[, mode])¶ Recursive directory creation function. Like
mkdir()
, but makes all intermediate-level directories needed to contain the leaf directory. Raises anerror
exception if the leaf directory already exists or cannot be created. The default mode is0777
(octal).The mode parameter is passed to
mkdir()
; see the mkdir() description for how it is interpreted.注解
makedirs()
will become confused if the path elements to create includeos.pardir
.1.5.2 新版功能.
在 2.3 版更改: This function now handles UNC paths correctly.
-
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.Availability: Unix.
-
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)¶ 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)
.在 2.6 版更改: If the path is a Unicode object the result will also be a Unicode object.
Availability: Unix.
-
os.
remove
(path)¶ Remove (delete) the file path. If path is a directory,
OSError
is raised; seermdir()
below to remove a directory. This is identical to theunlink()
function documented below. 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.Availability: Unix, Windows.
-
os.
removedirs
(path)¶ 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.1.5.2 新版功能.
-
os.
rename
(src, dst)¶ Rename the file or directory src to dst. If dst is a directory,
OSError
will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists,OSError
will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file.Availability: Unix, Windows.
-
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()
.1.5.2 新版功能.
注解
This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file.
-
os.
rmdir
(path)¶ Remove (delete) the directory path. Only works when the directory is empty, otherwise,
OSError
is raised. In order to remove whole directory trees,shutil.rmtree()
can be used.Availability: Unix, Windows.
-
os.
stat
(path)¶ Perform the equivalent of a
stat()
system call on the given path. (This function follows symlinks; to stat a symlink uselstat()
.)The return value is an object whose attributes correspond to the members of the
stat
structure, namely:st_mode
- protection bits,st_ino
- inode number,st_dev
- device,st_nlink
- number of hard links,st_uid
- user id of owner,st_gid
- group id of owner,st_size
- size of file, in bytes,st_atime
- time of most recent access,st_mtime
- time of most recent content modification,st_ctime
- platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)
在 2.3 版更改: If
stat_float_times()
returnsTrue
, the time values are floats, measuring seconds. Fractions of a second may be reported if the system supports that. Seestat_float_times()
for further discussion.On some Unix systems (such as Linux), the following attributes may also be available:
st_blocks
- number of 512-byte blocks allocated for filest_blksize
- filesystem blocksize for efficient file system I/Ost_rdev
- type of device if an inode devicest_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 numberst_birthtime
- time of file creation
On RISCOS systems, the following attributes are also available:
st_ftype
(file type)st_attrs
(attributes)st_obtype
(object type).
注解
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.For backward compatibility, the return value of
stat()
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.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.)示例:
>>> import os >>> statinfo = os.stat('somefile.txt') >>> statinfo (33188, 422511, 769, 1, 1032, 100, 926, 1105022698,1105022732, 1105022732) >>> statinfo.st_size 926
Availability: Unix, Windows.
在 2.2 版更改: Added access to values as attributes of the returned object.
在 2.5 版更改: Added
st_gen
andst_birthtime
.
-
os.
stat_float_times
([newvalue])¶ Determine whether
stat_result
represents time stamps as float objects. If newvalue isTrue
, future calls tostat()
return floats, if it isFalse
, future calls return ints. If newvalue is omitted, return the current setting.For compatibility with older Python versions, accessing
stat_result
as a tuple always returns integers.在 2.5 版更改: Python now returns float values by default. Applications which do not work correctly with floating point time stamps can use this function to restore the old behaviour.
The resolution of the timestamps (that is the smallest possible fraction) depends on the system. Some systems only support second resolution; on these systems, the fraction will always be zero.
It is recommended that this setting is only changed at program startup time in the __main__ module; libraries should never change this setting. If an application uses a library that works incorrectly if floating point time stamps are processed, this application should turn the feature off until the library has been corrected.
-
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
.For backward compatibility, the return value is also accessible as a tuple whose values correspond to the attributes, in the order given above. The standard module
statvfs
defines constants that are useful for extracting information from astatvfs
structure when accessing it as a sequence; this remains useful when writing code that needs to work with versions of Python that don’t support accessing the fields as attributes.Availability: Unix.
在 2.2 版更改: Added access to values as attributes of the returned object.
-
os.
symlink
(source, link_name)¶ Create a symbolic link pointing to source named link_name.
Availability: Unix.
-
os.
tempnam
([dir[, prefix]])¶ Return a unique path name that is reasonable for creating a temporary file. This will be an absolute path that names a potential directory entry in the directory dir or a common location for temporary files if dir is omitted or
None
. If given and notNone
, prefix is used to provide a short prefix to the filename. Applications are responsible for properly creating and managing files created using paths returned bytempnam()
; no automatic cleanup is provided. On Unix, the environment variableTMPDIR
overrides dir, while on WindowsTMP
is used. The specific behavior of this function depends on the C library implementation; some aspects are underspecified in system documentation.警告
Use of
tempnam()
is vulnerable to symlink attacks; consider usingtmpfile()
(section 创建文件对象) instead.Availability: Unix, Windows.
-
os.
tmpnam
()¶ Return a unique path name that is reasonable for creating a temporary file. This will be an absolute path that names a potential directory entry in a common location for temporary files. Applications are responsible for properly creating and managing files created using paths returned by
tmpnam()
; no automatic cleanup is provided.警告
Use of
tmpnam()
is vulnerable to symlink attacks; consider usingtmpfile()
(section 创建文件对象) instead.Availability: Unix, Windows. This function probably shouldn’t be used on Windows, though: Microsoft’s implementation of
tmpnam()
always creates a name in the root directory of the current drive, and that’s generally a poor location for a temp file (depending on privileges, you may not even be able to open a file using this name).
-
os.
unlink
(path)¶ Remove (delete) the file path. This is the same function as
remove()
; theunlink()
name is its traditional Unix name.Availability: Unix, Windows.
-
os.
utime
(path, times)¶ Set the access and modified times of the file specified by path. If times is
None
, then the file’s access and modified times are set to the current time. (The effect is similar to running the Unix program touch on the path.) Otherwise, times must be a 2-tuple of numbers, of the form(atime, mtime)
which is used to set the access and modified times, respectively. Whether a directory can be given for path depends on whether the operating system implements directories as files (for example, Windows does not). Note that the exact times you set here may not be returned by a subsequentstat()
call, depending on the resolution with which your operating system records access and modification times; seestat()
.在 2.0 版更改: Added support for
None
for times.Availability: Unix, Windows.
-
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)
.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
listdir()
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.2.6 新版功能: The followlinks parameter.
注解
Be aware that setting followlinks to
True
can lead to infinite recursion if a link points to a parent directory of itself.walk()
does not keep track of the directories it visited already.注解
If you pass a relative pathname, don’t change the current working directory between resumptions of
walk()
.walk()
never changes the current directory, and assumes that its caller doesn’t either.This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:
import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum(getsize(join(root, name)) for name in files), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories
In the next example, walking the tree bottom-up is essential:
rmdir()
doesn’t allow deleting a directory before the directory is empty:# Delete everything reachable from the directory named in "top", # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files 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))
2.3 新版功能.
15.1.5. 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()
.Availability: Unix, Windows.
-
os.
execl
(path, arg0, arg1, ...)¶ -
os.
execle
(path, arg0, arg1, ..., env)¶ -
os.
execlp
(file, arg0, arg1, ...)¶ -
os.
execlpe
(file, arg0, arg1, ..., env)¶ -
os.
execv
(path, args)¶ -
os.
execve
(path, args, env)¶ -
os.
execvp
(file, args)¶ -
os.
execvpe
(file, args, env)¶ These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as
OSError
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.Availability: Unix, Windows.
-
os.
_exit
(n)¶ Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.
Availability: Unix, Windows.
The following exit codes are defined and can be used with _exit()
,
although they are not required. These are typically used for system programs
written in Python, such as a mail server’s external command delivery program.
注解
Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.
-
os.
EX_OK
¶ Exit code that means no error occurred.
Availability: Unix.
2.3 新版功能.
-
os.
EX_USAGE
¶ Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given.
Availability: Unix.
2.3 新版功能.
-
os.
EX_DATAERR
¶ Exit code that means the input data was incorrect.
Availability: Unix.
2.3 新版功能.
-
os.
EX_NOINPUT
¶ Exit code that means an input file did not exist or was not readable.
Availability: Unix.
2.3 新版功能.
-
os.
EX_NOUSER
¶ Exit code that means a specified user did not exist.
Availability: Unix.
2.3 新版功能.
-
os.
EX_NOHOST
¶ Exit code that means a specified host did not exist.
Availability: Unix.
2.3 新版功能.
-
os.
EX_UNAVAILABLE
¶ Exit code that means that a required service is unavailable.
Availability: Unix.
2.3 新版功能.
-
os.
EX_SOFTWARE
¶ Exit code that means an internal software error was detected.
Availability: Unix.
2.3 新版功能.
-
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.
2.3 新版功能.
-
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.
2.3 新版功能.
-
os.
EX_CANTCREAT
¶ Exit code that means a user specified output file could not be created.
Availability: Unix.
2.3 新版功能.
-
os.
EX_IOERR
¶ Exit code that means that an error occurred while doing I/O on some file.
Availability: Unix.
2.3 新版功能.
-
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.
2.3 新版功能.
-
os.
EX_PROTOCOL
¶ Exit code that means that a protocol exchange was illegal, invalid, or not understood.
Availability: Unix.
2.3 新版功能.
-
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.
2.3 新版功能.
-
os.
EX_CONFIG
¶ Exit code that means that some kind of configuration error occurred.
Availability: Unix.
2.3 新版功能.
-
os.
EX_NOTFOUND
¶ Exit code that means something like “an entry was not found”.
Availability: Unix.
2.3 新版功能.
-
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, Cygwin and OS/2 EMX have known issues when using fork() from a thread.
警告
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.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.2.7 新版功能: Windows support
-
os.
killpg
(pgid, sig)¶ Send the signal sig to the process group pgid.
Availability: Unix.
2.3 新版功能.
-
os.
nice
(increment)¶ Add increment to the process’s “niceness”. Return the new niceness.
Availability: Unix.
-
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
(...) -
os.
popen2
(...) -
os.
popen3
(...) -
os.
popen4
(...) Run child processes, returning opened pipes for communications. These functions are described in section 创建文件对象.
-
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.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)
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.1.6 新版功能.
-
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.
1.6 新版功能.
-
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.
1.6 新版功能.
-
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.
1.6 新版功能.
-
os.
startfile
(path[, operation])¶ 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).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. If you want to use an absolute path, make sure the first character is not a slash ('/'
); the underlying Win32ShellExecute()
function doesn’t work if it is. Use theos.path.normpath()
function to ensure that the path is properly encoded for Win32.Availability: Windows.
2.0 新版功能.
2.5 新版功能: The operation parameter.
-
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.On Unix, the return value is the exit status of the process encoded in the format specified for
wait()
. Note that POSIX does not specify the meaning of the return value of the Csystem()
function, so the return value of the Python function is system-dependent.On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable
COMSPEC
: on command.com systems (Windows 95, 98 and ME) this is always0
; on cmd.exe systems (Windows NT, 2000 and XP) this is 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.Availability: Unix, Windows.
-
os.
times
()¶ Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children’s user time, children’s system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. On Windows, only the first two items are filled, the others are zero.
Availability: Unix, Windows
-
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.
Availability: Unix.
-
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
OSError
is raised with the value of errno when the syscall returns -1.On Windows: Wait for completion of a process given by process handle pid, and return a tuple containing pid, and its exit status shifted left by 8 bits (shifting makes cross-platform use of the function easier). A pid less than or equal to
0
has no special meaning on Windows, and raises an exception. The value of integer 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.
-
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()
.Availability: Unix.
2.5 新版功能.
-
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()
.Availability: Unix.
2.5 新版功能.
-
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.
2.3 新版功能.
-
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.
2.3 新版功能.
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
.Availability: Unix.
2.3 新版功能.
-
os.
WIFCONTINUED
(status)¶ Return
True
if the process has been continued from a job control stop, otherwise returnFalse
.Availability: Unix.
2.3 新版功能.
-
os.
WIFSTOPPED
(status)¶ Return
True
if the process has been stopped, otherwise returnFalse
.Availability: Unix.
-
os.
WIFSIGNALED
(status)¶ Return
True
if the process exited due to a signal, otherwise returnFalse
.Availability: Unix.
-
os.
WIFEXITED
(status)¶ Return
True
if the process exited using the exit(2) system call, otherwise returnFalse
.Availability: Unix.
-
os.
WEXITSTATUS
(status)¶ If
WIFEXITED(status)
is true, return the integer parameter to the exit(2) system call. Otherwise, the return value is meaningless.Availability: Unix.
-
os.
WSTOPSIG
(status)¶ Return the signal which caused the process to stop.
Availability: Unix.
-
os.
WTERMSIG
(status)¶ Return the signal which caused the process to exit.
Availability: Unix.
15.1.6. 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.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.
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.
2.3 新版功能.
-
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
.2.2 新版功能.
-
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.
15.1.7. Miscellaneous Functions¶
-
os.
urandom
(n)¶ Return a string of n random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a UNIX-like system this will query
/dev/urandom
, and on Windows it will useCryptGenRandom()
. If a randomness source is not found,NotImplementedError
will be raised.For an easy-to-use interface to the random number generator provided by your platform, please see
random.SystemRandom
.2.4 新版功能.