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
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.
os.
名称
¶
操作系统的名称从属模块导入。目前有注册下列名称:
'posix'
,
'nt'
,
'os2'
,
'ce'
,
'java'
,
'riscos'
.
另请参阅
sys.platform
有更细粒度。
os.uname()
给出系统从属版本信息。
The
platform
模块提供系统身份的详细校验。
这些函数和数据项提供信息并运转于当前进程和用户。
os.
environ
¶
A
映射
对象表示字符串环境。例如,
environ['HOME']
是 Home (主) 目录的路径名 (在某些平台),且相当于
getenv("HOME")
在 C。
捕获此映射,当首次
os
模块被导入时,通常在 Python 启动期间,属于处理
site.py
。在此时间后对环境做出的改变,不会反射在
os.environ
, 除了做出的改变是通过修改
os.environ
直接。
若平台支持
putenv()
函数,此映射可用于修改环境及查询环境。
putenv()
将被自动调用当映射被修改时。
注意
调用
putenv()
直接不改变
os.environ
,因此最好修改
os.environ
.
注意
在某些平台,括 FreeBSD 和 Mac OS X,设置
environ
可能导致内存泄漏。参考系统文档编制了解
putenv()
.
若
putenv()
is not provided, a modified copy of this mapping may be passed to the appropriate process-creation functions to cause child processes to use a modified environment.
若平台支持
unsetenv()
function, you can delete items in this mapping to unset environment variables.
unsetenv()
会被自动调用当删除项从
os.environ
,和当某一
pop()
or
clear()
方法被调用。
2.6 版改变:
Also unset environment variables when calling
os.environ.clear()
and
os.environ.pop()
.
os.
chdir
(
path
)
os.
fchdir
(
fd
)
os.
getcwd
(
)
这些函数的描述,位于 文件和目录 .
os.
ctermid
(
)
¶
返回进程控制终端对应的文件名。
可用性:Unix。
os.
getegid
(
)
¶
返回当前进程的有效组 ID。这对应当前进程正执行文件中的 set id 位。
可用性:Unix。
os.
geteuid
(
)
¶
返回当前进程的有效用户 ID。
可用性:Unix。
os.
getgid
(
)
¶
返回当前进程的真实组 ID。
可用性:Unix。
os.
getgroups
(
)
¶
返回关联当前进程的补充组 ID 的列表。
可用性:Unix。
注意
在 Mac OS X,
getgroups()
behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of
10.5
or earlier,
getgroups()
returns the list of effective group ids associated with the current user process; this list is limited to a system-defined number of entries, typically 16, and may be modified by calls to
setgroups()
if suitably privileged. If built with a deployment target greater than
10.5
,
getgroups()
returns the current group access list for the user associated with the effective user id of the process; the group access list may change over the lifetime of the process, it is not affected by calls to
setgroups()
, and its length is not limited to 16. The deployment target value,
MACOSX_DEPLOYMENT_TARGET
, can be obtained with
sysconfig.get_config_var()
.
os.
initgroups
(
username
,
gid
)
¶
Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified group id.
可用性:Unix。
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, or
pwd.getpwuid(os.getuid())[0]
to get the login name of the process’s real user id.
可用性:Unix。
os.
getpgid
(
pid
)
¶
返回进程的进程组 ID 采用进程 ID pid 。若 pid 为 0,返回当前进程的进程组 ID。
可用性:Unix。
2.3 版新增。
os.
getpgrp
(
)
¶
返回当前进程组的 ID。
可用性:Unix。
os.
getpid
(
)
¶
返回当前进程 ID。
可用性:Unix Windows。
os.
getppid
(
)
¶
Return the parent’s process id.
可用性:Unix。
os.
getresuid
(
)
¶
返回表示当前进程真实、有效及保存用户 ID 的元组 (ruid, euid, suid)。
可用性:Unix。
2.7 版新增。
os.
getresgid
(
)
¶
返回表示当前进程真实、有效及保存组 ID 的元组 (rgid, egid, sgid)。
可用性:Unix。
2.7 版新增。
os.
getuid
(
)
¶
返回当前进程的真实用户 ID。
可用性:Unix。
os.
getenv
(
varname
[
,
值
]
)
¶
返回值对于环境变量
varname
若存在,或
value
若它没有。
value
默认为
None
.
可用性:大多数风味的 Unix、Windows。
os.
putenv
(
varname
,
值
)
¶
设置环境变量命名
varname
到字符串
value
。对环境的这种改变会影响子进程的启动采用
os.system()
,
popen()
or
fork()
and
execv()
.
可用性:大多数风味的 Unix、Windows。
注意
在某些平台,括 FreeBSD 和 Mac OS X,设置
environ
may cause memory leaks. Refer to the system documentation for putenv.
当
putenv()
is supported, assignments to items in
os.environ
会被自动翻译成相应调用
putenv()
;不管怎样,调用
putenv()
不更新
os.environ
, so it is actually preferable to assign to items of
os.environ
.
os.
setegid
(
egid
)
¶
设置当前进程的有效组 ID。
可用性:Unix。
os.
seteuid
(
euid
)
¶
设置当前进程的有效用户 ID。
可用性:Unix。
os.
setgid
(
gid
)
¶
设置当前进程的组 ID。
可用性:Unix。
os.
setgroups
(
groups
)
¶
Set the list of supplemental group ids associated with the current process to groups . groups must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser.
可用性:Unix。
2.2 版新增。
注意
On Mac OS X, the length of
groups
may not exceed the system-defined maximum number of effective group ids, typically 16. See the documentation for
getgroups()
for cases where it may not return the same group list set by calling setgroups().
os.
setpgrp
(
)
¶
调用系统调用
setpgrp()
or
setpgrp(0, 0)
depending on which version is implemented (if any). See the Unix manual for the semantics.
可用性:Unix。
os.
setpgid
(
pid
,
pgrp
)
¶
调用系统调用
setpgid()
to set the process group id of the process with id
pid
to the process group with id
pgrp
。见 Unix 手册了解语义。
可用性:Unix。
os.
setregid
(
rgid
,
egid
)
¶
设置当前进程的真实有效组 ID。
可用性:Unix。
os.
setresgid
(
rgid
,
egid
,
sgid
)
¶
设置当前进程的真实、有效及保存组 ID。
可用性:Unix。
2.7 版新增。
os.
setresuid
(
ruid
,
euid
,
suid
)
¶
设置当前进程的真实、有效及保存用户 ID。
可用性:Unix。
2.7 版新增。
os.
setreuid
(
ruid
,
euid
)
¶
设置当前进程的真实和有效用户 ID。
可用性:Unix。
os.
getsid
(
pid
)
¶
调用系统调用
getsid()
。见 Unix 手册了解语义。
可用性:Unix。
2.4 版新增。
os.
setsid
(
)
¶
调用系统调用
setsid()
。见 Unix 手册了解语义。
可用性:Unix。
os.
setuid
(
uid
)
¶
设置当前进程的用户 ID。
可用性:Unix。
os.
strerror
(
code
)
¶
Return the error message corresponding to the error code in
code
. On platforms where
strerror()
返回
NULL
when given an unknown error number,
ValueError
被引发。
可用性:Unix Windows。
os.
umask
(
mask
)
¶
设置当前数值 umask 并返回先前 umask。
可用性: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 is
socket.gethostname()
或者甚至
socket.gethostbyaddr(socket.gethostname())
.
可用性:最近风味的 Unix。
os.
unsetenv
(
varname
)
¶
取消设置 (删除) 环境变量命名
varname
。对环境的这种改变会影响子进程的启动采用
os.system()
,
popen()
or
fork()
and
execv()
.
当
unsetenv()
is supported, deletion of items in
os.environ
is automatically translated into a corresponding call to
unsetenv()
;不管怎样,调用
unsetenv()
不更新
os.environ
, so it is actually preferable to delete items of
os.environ
.
可用性:大多数风味的 Unix、Windows。
These functions create new file objects. (See also
open()
)。
os.
fdopen
(
fd
[
,
mode
[
,
bufsize
]
]
)
¶
返回的打开文件对象被连接到文件描述符
fd
。
mode
and
bufsize
arguments have the same meaning as the corresponding arguments to the built-in
open()
function. If
fdopen()
raises an exception, it leaves
fd
untouched (unclosed).
可用性:Unix Windows。
Changed in version 2.3:
When specified, the
mode
argument must now start with one of the letters
'r'
,
'w'
,或
'a'
, otherwise a
ValueError
被引发。
Changed in version 2.5:
On Unix, when the
mode
argument starts with
'a'
,
O_APPEND
flag is set on the file descriptor (which the
fdopen()
implementation already does on most platforms).
os.
popen
(
命令
[
,
mode
[
,
bufsize
]
]
)
¶
Open a pipe to or from
命令
。返回值是连接管道的打开文件对象,可以读取或写入从属
mode
is
'r'
(默认) 或
'w'
。
bufsize
自变量拥有的含义如同相应自变量在内置
open()
function. The exit status of the command (encoded in the format specified for
wait()
) is available as the return value of the
close()
method of the file object, except that when the exit status is zero (termination without errors),
None
被返回。
可用性:Unix Windows。
Deprecated since version 2.6:
This function is obsolete. Use the
subprocess
module. Check especially the
替换较旧函数采用 subprocess 模块
章节。
Changed in version 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.
可用性:Unix Windows。
There are a number of different
popen*()
functions that provide slightly different ways to create subprocesses.
Deprecated since version 2.6:
All of the
popen*()
functions are obsolete. Use the
subprocess
模块。
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()
)。若
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
]
]
)
¶
执行
cmd
as a sub-process and return the file objects
(child_stdin,
child_stdout)
.
Deprecated since version 2.6:
This function is obsolete. Use the
subprocess
module. Check especially the
替换较旧函数采用 subprocess 模块
章节。
可用性:Unix Windows。
2.0 版新增。
os.
popen3
(
cmd
[
,
mode
[
,
bufsize
]
]
)
¶
执行
cmd
as a sub-process and return the file objects
(child_stdin,
child_stdout, child_stderr)
.
Deprecated since version 2.6:
This function is obsolete. Use the
subprocess
module. Check especially the
替换较旧函数采用 subprocess 模块
章节。
可用性:Unix Windows。
2.0 版新增。
os.
popen4
(
cmd
[
,
mode
[
,
bufsize
]
]
)
¶
执行
cmd
as a sub-process and return the file objects
(child_stdin,
child_stdout_and_stderr)
.
Deprecated since version 2.6:
This function is obsolete. Use the
subprocess
module. Check especially the
替换较旧函数采用 subprocess 模块
章节。
可用性:Unix Windows。
2.0 版新增。
(注意,
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.
这些函数运转于使用文件描述符引用的 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 .
可用性:Unix Windows。
注意
此函数旨在低级 I/O 且必须应用于文件描述符如返回通过
os.open()
or
pipe()
。要关闭 "文件对象" 返回通过内置函数
open()
或通过
popen()
or
fdopen()
,使用其
close()
方法。
os.
closerange
(
fd_low
,
fd_high
)
¶
关闭所有文件描述符从 fd_low (包括在内) 到 fd_high (exclusive), ignoring errors. Equivalent to:
for fd in xrange(fd_low, fd_high): try: os.close(fd) except OSError: pass
可用性:Unix Windows。
2.6 版新增。
os.
dup
(
fd
)
¶
返回复制的文件描述符 fd .
可用性:Unix Windows。
os.
dup2
(
fd
,
fd2
)
¶
复制文件描述符 fd to fd2 , closing the latter first if necessary.
可用性:Unix Windows。
os.
fchown
(
fd
,
uid
,
gid
)
¶
更改所有者和组 ID 对于文件给出通过 fd 到数值 uid and gid 。要使某一 ID 留下不变,将它设为 -1。
可用性:Unix。
2.6 版新增。
os.
fdatasync
(
fd
)
¶
强制写入文件采用文件描述符 fd 到磁盘。不强制更新元数据。
可用性:Unix。
注意
该函数不可用于 MacOS。
os.
fpathconf
(
fd
,
名称
)
¶
返回打开文件相关的系统配置信息。
name
specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the
pathconf_names
dictionary. For configuration variables not included in that mapping, passing an integer for
name
is also accepted.
若
name
是字符串且未知,
ValueError
被引发。若特定值对于
name
主机系统不支持,即使包括在
pathconf_names
,
OSError
被引发采用
errno.EINVAL
对于错误编号。
可用性:Unix。
os.
fstatvfs
(
fd
)
¶
Return information about the filesystem containing the file associated with file descriptor
fd
,像
statvfs()
.
可用性:Unix。
os.
fsync
(
fd
)
¶
强制写入文件采用文件描述符
fd
到磁盘。在 Unix,这调用本机
fsync()
函数;在 Windows,MS
_commit()
函数。
If you’re starting with a Python file object
f
,首先做
f.flush()
,然后做
os.fsync(f.fileno())
,以确保所有内部缓冲关联的
f
被写入磁盘。
Availability: Unix, and Windows starting in 2.2.3.
os.
ftruncate
(
fd
,
length
)
¶
截取文件所对应的文件描述符 fd ,因此最多 length 字节大小。
可用性:Unix。
os.
isatty
(
fd
)
¶
返回
True
若文件描述符
fd
被打开 且已连接到像 tty 设备,否则
False
.
os.
lseek
(
fd
,
pos
,
how
)
¶
Set the current position of file descriptor
fd
to position
pos
, modified by
how
:
SEEK_SET
or
0
to set the position relative to the beginning of the file;
SEEK_CUR
or
1
to set it relative to the current position;
SEEK_END
or
2
to set it relative to the end of the file. Return the new cursor position in bytes, starting from the beginning.
可用性:Unix Windows。
os.
SEEK_SET
¶
os.
SEEK_CUR
¶
os.
SEEK_END
¶
参数用于
lseek()
函数。它们的值分别为 0、1、和 2。
Availability: Windows, Unix.
2.5 版新增。
os.
open
(
file
,
flags
[
,
mode
]
)
¶
打开文件
file
和设置各种标志根据
flags
且其模式可能根据
mode
。默认
mode
is
0777
(octal), and the current umask value is first masked out. Return the file descriptor for the newly opened file.
对于 flags 和 mode 值的描述,见 C 运行时文档编制;flags 常量 (像
O_RDONLY
and
O_WRONLY
) are defined in this module too (see
open() flag constants
). In particular, on Windows adding
O_BINARY
需要以二进制模式打开文件。
可用性:Unix Windows。
注意
此函数旨在低级 I/O。对于正常用法,使用内置函数
open()
, which returns a “file object” with
read()
and
write()
methods (and many more). To wrap a file descriptor in a “file object”, use
fdopen()
.
os.
openpty
(
)
¶
打开新的伪终端对。返回一对文件描述符
(master,
slave)
for the pty and the tty, respectively. For a (slightly) more portable approach, use the
pty
模块。
可用性:某些风味的 Unix。
os.
pipe
(
)
¶
创建管道。返回一对文件描述符
(r, w)
usable for reading and writing, respectively.
可用性:Unix Windows。
os.
read
(
fd
,
n
)
¶
读取最多 n 字节从文件描述符 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.
可用性:Unix Windows。
注意
此函数旨在低级 I/O 且必须应用于文件描述符如返回通过
os.open()
or
pipe()
. To read a “file object” returned by the built-in function
open()
或通过
popen()
or
fdopen()
,或
sys.stdin
,使用其
read()
or
readline()
方法。
os.
tcgetpgrp
(
fd
)
¶
Return the process group associated with the terminal given by
fd
(an open file descriptor as returned by
os.open()
).
可用性:Unix。
os.
tcsetpgrp
(
fd
,
pg
)
¶
Set the process group associated with the terminal given by
fd
(an open file descriptor as returned by
os.open()
) 到
pg
.
可用性:Unix。
os.
ttyname
(
fd
)
¶
Return a string which specifies the terminal device associated with file descriptor fd 。若 fd is not associated with a terminal device, an exception is raised.
可用性:Unix。
os.
write
(
fd
,
str
)
¶
写入字符串 str 到文件描述符 fd 。返回实际写入字节数。
可用性:Unix Windows。
注意
此函数旨在低级 I/O 且必须应用于文件描述符如返回通过
os.open()
or
pipe()
. To write a “file object” returned by the built-in function
open()
或通过
popen()
or
fdopen()
,或
sys.stdout
or
sys.stderr
,使用其
write()
方法。
open()
标志常量
¶
下列常量是选项对于
flags
参数用于
open()
函数。可以组合它们使用按位 OR 运算符
|
。它们中的一些不可用于所有平台。对于它们的可用性和用法的描述,请翻阅
open(2)
手册页在 Unix 或
MSDN
在 Windows。
os.
O_RDONLY
¶
os.
O_WRONLY
¶
os.
O_RDWR
¶
os.
O_APPEND
¶
os.
O_CREAT
¶
os.
O_EXCL
¶
os.
O_TRUNC
¶
以上常量只可用于 Unix 和 Windows。
os.
O_DSYNC
¶
os.
O_RSYNC
¶
os.
O_SYNC
¶
os.
O_NDELAY
¶
os.
O_NONBLOCK
¶
os.
O_NOCTTY
¶
以上常量只可用于 Unix。
os.
O_BINARY
¶
os.
O_NOINHERIT
¶
os.
O_SHORT_LIVED
¶
os.
O_TEMPORARY
¶
os.
O_RANDOM
¶
os.
O_SEQUENTIAL
¶
os.
O_TEXT
¶
以上常量只可用于 Windows。
os.
O_ASYNC
¶
os.
O_DIRECT
¶
os.
O_DIRECTORY
¶
os.
O_NOFOLLOW
¶
os.
O_NOATIME
¶
os.
O_SHLOCK
¶
os.
O_EXLOCK
¶
以上常量是扩展,且不存在若 C 库未定义它们。
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
应该为
F_OK
to test the existence of
path
, or it can be the inclusive OR of one or more of
R_OK
,
W_OK
,和
X_OK
to test permissions. Return
True
if access is allowed,
False
if not. See the Unix man page
access(2)
了解更多信息。
可用性:Unix Windows。
注意
使用
access()
to check if a user is authorized to e.g. open a file before actually doing so using
open()
creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use
EAFP
techniques. For example:
if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read() return "some default data"
is better written as:
try: fp = open("myfile") except 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
)
¶
将当前工作目录更改成 path .
可用性:Unix Windows。
os.
fchdir
(
fd
)
¶
Change the current working directory to the directory represented by the file descriptor fd 。描述符必须引用打开目录,而不是打开文件。
可用性:Unix。
2.3 版新增。
os.
getcwd
(
)
¶
返回当前工作目录的字符串表示。
可用性:Unix Windows。
os.
getcwdu
(
)
¶
Return a Unicode object representing the current working directory.
可用性:Unix Windows。
2.3 版新增。
os.
chflags
(
path
,
flags
)
¶
设置标志为
path
到数值
flags
.
flags
may take a combination (bitwise OR) of the following values (as defined in the
stat
模块):
可用性:Unix。
2.6 版新增。
os.
chroot
(
path
)
¶
Change the root directory of the current process to path . Availability: Unix.
2.2 版新增。
os.
chmod
(
path
,
mode
)
¶
改变模式为
path
到数值
mode
.
mode
may take one of the following values (as defined in the
stat
module) or bitwise ORed combinations of them:
可用性:Unix Windows。
注意
尽管 Windows 支持
chmod()
, you can only set the file’s read-only flag with it (via the
stat.S_IWRITE
and
stat.S_IREAD
constants or a corresponding integer value). All other bits are ignored.
os.
chown
(
path
,
uid
,
gid
)
¶
更改所有者和组 ID 为 path 到数值 uid and gid 。要使某一 ID 留下不变,将它设为 -1。
可用性:Unix。
os.
lchflags
(
path
,
flags
)
¶
设置标志为
path
到数值
flags
,像
chflags()
, but do not follow symbolic links.
可用性:Unix。
2.6 版新增。
os.
lchmod
(
path
,
mode
)
¶
改变模式为
path
到数值
mode
. If path is a symlink, this affects the symlink rather than the target. See the docs for
chmod()
了解可能值对于
mode
.
可用性:Unix。
2.6 版新增。
os.
lchown
(
path
,
uid
,
gid
)
¶
更改所有者和组 ID 为 path 到数值 uid and gid . This function will not follow symbolic links.
可用性:Unix。
2.3 版新增。
os.
link
(
source
,
link_name
)
¶
创建的硬链接指向 source 命名 link_name .
可用性:Unix。
os.
listdir
(
path
)
¶
返回包含条目名称的列表,在给定目录
path
. The list is in arbitrary order. It does not include the special entries
'.'
and
'..'
即使它们呈现于目录中。
可用性:Unix Windows。
Changed in version 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
)
¶
履行等效
lstat()
系统调用按给定路径。类似
stat()
, but does not follow symbolic links. On platforms that do not support symbolic links, this is an alias for
stat()
.
os.
mkfifo
(
path
[
,
mode
]
)
¶
创建 FIFO (命名管道) 命名
path
采用数值模式
mode
。默认
mode
is
0666
(octal). The current umask value is first masked out from the mode.
可用性: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 that
mkfifo()
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
,和
stat.S_IFIFO
(those constants are available in
stat
). For
stat.S_IFCHR
and
stat.S_IFBLK
,
device
defines the newly created device special file (probably using
os.makedev()
),否则被忽略。
2.3 版新增。
os.
major
(
device
)
¶
Extract the device major number from a raw device number (usually the
st_dev
or
st_rdev
字段来自
stat
).
2.3 版新增。
os.
minor
(
device
)
¶
Extract the device minor number from a raw device number (usually the
st_dev
or
st_rdev
字段来自
stat
).
2.3 版新增。
os.
makedev
(
major
,
minor
)
¶
Compose a raw device number from the major and minor device numbers.
2.3 版新增。
os.
mkdir
(
path
[
,
mode
]
)
¶
创建目录命名
path
采用数值模式
mode
。默认
mode
is
0777
(octal). If the directory already exists,
OSError
被引发。
在某些系统,
mode
被忽略。若使用它,会先屏蔽掉当前 umask 值。若除了后 9 位 (即:以八进制表示后 3 位对于
mode
) 被设置,它们的含义从属平台。在某些平台,会忽略它们且应调用
chmod()
以明确设置它们。
创建临时目录也是可能的;见
tempfile
模块的
tempfile.mkdtemp()
函数。
可用性:Unix Windows。
os.
makedirs
(
path
[
,
mode
]
)
¶
递归目录创建函数。像
mkdir()
, but makes all intermediate-level directories needed to contain the leaf directory. Raises an
error
exception if the leaf directory already exists or cannot be created. The default
mode
is
0777
(octal).
The
mode
参数会被传递给
mkdir()
;见
mkdir() 描述
for how it is interpreted.
注意
makedirs()
会变得困惑若要创建的路径元素包含
os.pardir
.
1.5.2 版新增。
Changed in version 2.3: This function now handles UNC paths correctly.
os.
pathconf
(
path
,
名称
)
¶
Return system configuration information relevant to a named file.
name
specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the
pathconf_names
dictionary. For configuration variables not included in that mapping, passing an integer for
name
is also accepted.
若
name
是字符串且未知,
ValueError
被引发。若特定值对于
name
主机系统不支持,即使包括在
pathconf_names
,
OSError
被引发采用
errno.EINVAL
对于错误编号。
可用性:Unix。
os.
pathconf_names
¶
字典映射的名称接受通过
pathconf()
and
fpathconf()
to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system. Availability: Unix.
os.
readlink
(
path
)
¶
返回符号链接指向路径的表示字符串。结果可能是绝对 (或相对) 路径名;若是相对的,可以将它转换成绝对路径名使用
os.path.join(os.path.dirname(path),
result)
.
2.6 版改变: 若 path is a Unicode object the result will also be a Unicode object.
可用性:Unix。
os.
remove
(
path
)
¶
移除 (删除) 文件
path
。若
path
is a directory,
OSError
被引发;见
rmdir()
below to remove a directory. This is identical to the
unlink()
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.
可用性:Unix Windows。
os.
removedirs
(
path
)
¶
递归移除目录。工作像
rmdir()
除若成功移除叶目录外,
removedirs()
会试着依次移除提及的每个父级目录在
path
直到引发错误 (被忽略,因为通常意味着父级目录非空)。例如,
os.removedirs('foo/bar/baz')
会先移除目录
'foo/bar/baz'
,然后移除
'foo/bar'
and
'foo'
若它们为空。引发
OSError
若无法成功移除叶目录。
1.5.2 版新增。
os.
rename
(
src
,
dst
)
¶
重命名文件或目录
src
to
dst
。若
dst
is a directory,
OSError
will be raised. On Unix, if
dst
exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if
src
and
dst
are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if
dst
already exists,
OSError
will be raised even if it is a file; there may be no way to implement an atomic rename when
dst
names an existing file.
可用性:Unix Windows。
os.
renames
(
old
,
new
)
¶
目录 (或文件) 递归重命名函数。工作像
rename()
,除首先会试图创建使新路径名工作良好所需的任何中间体目录外。重命名后,会修剪掉旧名称最右路径段的对应目录使用
removedirs()
.
1.5.2 版新增。
注意
此函数创建新目录结构时可能失败,若缺乏移除叶目录 (或文件) 所需的权限。
os.
rmdir
(
path
)
¶
移除 (删除) 目录
path
. Only works when the directory is empty, otherwise,
OSError
is raised. In order to remove whole directory trees,
shutil.rmtree()
可以使用。
可用性: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 use
lstat()
)。
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)
Changed in version 2.3:
若
stat_float_times()
返回
True
, the time values are floats, measuring seconds. Fractions of a second may be reported if the system supports that. See
stat_float_times()
for further discussion.
在某些 Unix 系统 (譬如 Linux),下列属性也可能可用:
st_blocks
- number of 512-byte blocks allocated for file
st_blksize
- filesystem blocksize for efficient file system I/O
st_rdev
- type of device if an inode device
st_flags
- user defined flags for file
在其它 Unix 系统 (譬如 FreeBSD),下列属性可能可用 (但可能才填写当 root 试着使用它们时):
st_gen
- file generation number
st_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).
注意
准确含义和分辨率对于
st_atime
,
st_mtime
,和
st_ctime
属性从属操作系统和文件系统。例如,Windows 系统使用 FAT (或 FAT32) 文件系统,
st_mtime
拥有 2 秒分辨率,和
st_atime
只有 1 天的分辨率。见操作系统文档编制了解细节。
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 the
stat
结构,按次序
st_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.
标准模块
stat
定义的函数和常量很有用为提取信息从
stat
结构 (在 Windows,某些项以虚设值填充)。
范例:
>>> import os >>> statinfo = os.stat('somefile.txt') >>> statinfo (33188, 422511, 769, 1, 1032, 100, 926, 1105022698,1105022732, 1105022732) >>> statinfo.st_size 926
可用性:Unix Windows。
2.2 版改变: Added access to values as attributes of the returned object.
Changed in version 2.5:
添加
st_gen
and
st_birthtime
.
os.
stat_float_times
(
[
newvalue
]
)
¶
Determine whether
stat_result
represents time stamps as float objects. If
newvalue
is
True
, future calls to
stat()
return floats, if it is
False
, future calls return ints. If
newvalue
is omitted, return the current setting.
For compatibility with older Python versions, accessing
stat_result
以元组形式始终返回整数。
Changed in version 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
)
¶
履行
statvfs()
system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the
statvfs
structure, namely:
f_bsize
,
f_frsize
,
f_blocks
,
f_bfree
,
f_bavail
,
f_files
,
f_ffree
,
f_favail
,
f_flag
,
f_namemax
.
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 a
statvfs
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.
可用性:Unix。
2.2 版改变: Added access to values as attributes of the returned object.
os.
symlink
(
source
,
link_name
)
¶
创建的符号链接指向 source 命名 link_name .
可用性: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
被省略或
None
. If given and not
None
,
prefix
is used to provide a short prefix to the filename. Applications are responsible for properly creating and managing files created using paths returned by
tempnam()
; no automatic cleanup is provided. On Unix, the environment variable
TMPDIR
overrides
dir
, while on Windows
TMP
is used. The specific behavior of this function depends on the C library implementation; some aspects are underspecified in system documentation.
警告
使用
tempnam()
is vulnerable to symlink attacks; consider using
tmpfile()
(section
文件对象创建
) 代替。
可用性: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.
警告
使用
tmpnam()
is vulnerable to symlink attacks; consider using
tmpfile()
(section
文件对象创建
) 代替。
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
)
¶
移除 (删除) 文件
path
. This is the same function as
remove()
;
unlink()
name is its traditional Unix name.
可用性:Unix Windows。
os.
utime
(
path
,
times
)
¶
设置文件的访问和修改时间指定通过
path
。若
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 subsequent
stat()
调用,从属操作系统记录访问时间和修改时间的分辨率; 见
stat()
.
Changed in version 2.0:
添加支持
None
for
times
.
可用性: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
本身),它产生 3 元组
(dirpath, dirnames,
filenames)
.
dirpath
is a string, the path to the directory.
dirnames
is a list of the names of the subdirectories in
dirpath
(excluding
'.'
and
'..'
).
filenames
is a list of the names of the non-directory files in
dirpath
. Note that the names in the lists contain no path components. To get a full path (which begins with
top
) to a file or directory in
dirpath
, do
os.path.join(dirpath, name)
.
若可选自变量
topdown
is
True
or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If
topdown
is
False
, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of
topdown
, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.
当
topdown
is
True
, the caller can modify the
dirnames
list in-place (perhaps using
del
or slice assignment), and
walk()
will only recurse into the subdirectories whose names remain in
dirnames
; this can be used to prune the search, impose a specific order of visiting, or even to inform
walk()
about directories the caller creates or renames before it resumes
walk()
again. Modifying
dirnames
当
topdown
is
False
has no effect on the behavior of the walk, because in bottom-up mode the directories in
dirnames
are generated before
dirpath
itself is generated.
By default, errors from the
listdir()
call are ignored. If optional argument
onerror
is specified, it should be a function; it will be called with one argument, an
OSError
instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the
filename
attribute of the exception object.
默认情况下,
walk()
will not walk down into symbolic links that resolve to directories. Set
followlinks
to
True
to visit directories pointed to by symlinks, on systems that support them.
2.6 版新增: The followlinks 参数。
注意
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 版新增。
这些函数可用于创建和管理进程。
The various
exec*
functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this is the
argv[0]
passed to a program’s
main()
。例如,
os.execv('/bin/echo',
['foo',
'bar'])
只会打印
bar
on standard output;
foo
will seem to be ignored.
os.
abort
(
)
¶
生成
SIGABRT
signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns an exit code of
3
. Be aware that calling this function will not call the Python signal handler registered for
SIGABRT
with
signal.signal()
.
可用性:Unix Windows。
os.
execl
(
path
,
arg0
,
arg1
,
...
)
¶
os.
execle
(
path
,
arg0
,
arg1
,
...
,
env
)
¶
os.
execlp
(
file
,
arg0
,
arg1
,
...
)
¶
os.
execlpe
(
file
,
arg0
,
arg1
,
...
,
env
)
¶
os.
execv
(
path
,
args
)
¶
os.
execve
(
path
,
args
,
env
)
¶
os.
execvp
(
file
,
args
)
¶
os.
execvpe
(
file
,
args
,
env
)
¶
These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as
OSError
异常。
The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using
sys.stdout.flush()
or
os.fsync()
before calling an
exec*
函数。
The “l” and “v” variants of the
exec*
functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the
execl*()
functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the
args
parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced.
The variants which include a “p” near the end (
execlp()
,
execlpe()
,
execvp()
,和
execvpe()
) 将使用
PATH
environment variable to locate the program
file
. When the environment is being replaced (using one of the
exec*e
variants, discussed in the next paragraph), the new environment is used as the source of the
PATH
variable. The other variants,
execl()
,
execle()
,
execv()
,和
execve()
, will not use the
PATH
variable to locate the executable;
path
must contain an appropriate absolute or relative path.
For
execle()
,
execlpe()
,
execve()
,和
execvpe()
(note that these all end in “e”), the
env
parameter must be a mapping which is used to define the environment variables for the new process (these are used instead of the current process’ environment); the functions
execl()
,
execlp()
,
execv()
,和
execvp()
all cause the new process to inherit the environment of the current process.
可用性:Unix Windows。
os.
_exit
(
n
)
¶
退出进程采用状态 n ,不调用清理处理程序、刷新 stdio 缓冲、等。
可用性:Unix Windows。
注意
退出的标准方式为
sys.exit(n)
.
_exit()
should normally only be used in the child process after a
fork()
.
The following exit codes are defined and can be used with
_exit()
, although they are not required. These are typically used for system programs written in Python, such as a mail server’s external command delivery program.
注意
Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.
os.
EX_OK
¶
退出代码意味着没有错误发生。
可用性:Unix。
2.3 版新增。
os.
EX_USAGE
¶
Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given.
可用性:Unix。
2.3 版新增。
os.
EX_DATAERR
¶
意味着输入数据不正确的退出代码。
可用性:Unix。
2.3 版新增。
os.
EX_NOINPUT
¶
Exit code that means an input file did not exist or was not readable.
可用性:Unix。
2.3 版新增。
os.
EX_NOUSER
¶
Exit code that means a specified user did not exist.
可用性:Unix。
2.3 版新增。
os.
EX_NOHOST
¶
Exit code that means a specified host did not exist.
可用性:Unix。
2.3 版新增。
os.
EX_UNAVAILABLE
¶
Exit code that means that a required service is unavailable.
可用性:Unix。
2.3 版新增。
os.
EX_SOFTWARE
¶
Exit code that means an internal software error was detected.
可用性: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.
可用性: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.
可用性:Unix。
2.3 版新增。
os.
EX_CANTCREAT
¶
Exit code that means a user specified output file could not be created.
可用性:Unix。
2.3 版新增。
os.
EX_IOERR
¶
Exit code that means that an error occurred while doing I/O on some file.
可用性: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.
可用性:Unix。
2.3 版新增。
os.
EX_PROTOCOL
¶
Exit code that means that a protocol exchange was illegal, invalid, or not understood.
可用性: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).
可用性:Unix。
2.3 版新增。
os.
EX_CONFIG
¶
Exit code that means that some kind of configuration error occurred.
可用性:Unix。
2.3 版新增。
os.
EX_NOTFOUND
¶
退出代码意味着某些事情像 an entry was not found。
可用性:Unix。
2.3 版新增。
os.
fork
(
)
¶
分叉子级进程。返回
0
在子级和子级进程 ID 在父级。若发生错误
OSError
被引发。
Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have known issues when using fork() from a thread.
警告
见
ssl
了解应用程序使用 SSL 模块采用 fork()。
可用性:Unix。
os.
forkpty
(
)
¶
分叉子级进程,使用新的伪终端作为子级进程的控制终端。返回一对
(pid, fd)
,其中
pid
is
0
in the child, the new child’s process id in the parent, and
fd
is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the
pty
模块。若出现错误
OSError
被引发。
可用性:某些风味的 Unix。
os.
kill
(
pid
,
sig
)
¶
发送信号
sig
给进程
pid
。可用主机平台特定信号常量的定义在
signal
模块。
Windows:
signal.CTRL_C_EVENT
and
signal.CTRL_BREAK_EVENT
信号是特殊信号,只能发送给共享公共控制台窗口的控制台进程 (如:某些子进程)。任何其它值的
sig
将导致进程被TerminateProcess API 无条件杀除,且退出代码将设为
sig
。Windows 版本的
kill()
此外还需杀除进程句柄。
New in version 2.7: Windows 支持
os.
killpg
(
pgid
,
sig
)
¶
发送信号 sig 给进程组 pgid .
可用性:Unix。
2.3 版新增。
os.
nice
(
increment
)
¶
添加 increment 到进程的 niceness (好感度)。返回新的好感度。
可用性:Unix。
os.
plock
(
op
)
¶
Lock program segments into memory. The value of
op
(defined in
<sys/lock.h>
) determines which segments are locked.
可用性:Unix。
os.
popen
(
...
)
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
)
¶
执行程序 path 在新的进程中。
(注意,
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the
替换较旧函数采用 subprocess 模块
章节。)
若
mode
is
P_NOWAIT
, this function returns the process id of the new process; if
mode
is
P_WAIT
, returns the process’s exit code if it exits normally, or
-signal
,其中
signal
is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with the
waitpid()
函数。
The “l” and “v” variants of the
spawn*
functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the
spawnl*()
functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the
args
parameter. In either case, the arguments to the child process must start with the name of the command being run.
The variants which include a second “p” near the end (
spawnlp()
,
spawnlpe()
,
spawnvp()
,和
spawnvpe()
) 将使用
PATH
environment variable to locate the program
file
. When the environment is being replaced (using one of the
spawn*e
variants, discussed in the next paragraph), the new environment is used as the source of the
PATH
variable. The other variants,
spawnl()
,
spawnle()
,
spawnv()
,和
spawnve()
, will not use the
PATH
variable to locate the executable;
path
must contain an appropriate absolute or relative path.
For
spawnle()
,
spawnlpe()
,
spawnve()
,和
spawnvpe()
(note that these all end in “e”), the
env
parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process’ environment); the functions
spawnl()
,
spawnlp()
,
spawnv()
,和
spawnvp()
all cause the new process to inherit the environment of the current process. Note that keys and values in the
env
dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of
127
.
作为范例,以下调用
spawnlp()
and
spawnvpe()
是等效的:
import os os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') L = ['cp', 'index.html', '/dev/null'] os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
可用性:Unix Windows。
spawnlp()
,
spawnlpe()
,
spawnvp()
and
spawnvpe()
不可用于 Windows。
spawnle()
and
spawnve()
在 Windows 不是线程安全的;建议使用
subprocess
模块代替。
New in version 1.6.
os.
P_NOWAIT
¶
os.
P_NOWAITO
¶
可能的值对于
mode
参数用于
spawn*
family of functions. If either of these values is given, the
spawn*()
functions will return as soon as the new process has been created, with the process id as the return value.
可用性:Unix Windows。
New in version 1.6.
os.
P_WAIT
¶
可能的值对于
mode
参数用于
spawn*
family of functions. If this is given as
mode
,
spawn*()
functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or
-signal
若信号杀除进程。
可用性:Unix Windows。
New in version 1.6.
os.
P_DETACH
¶
os.
P_OVERLAY
¶
可能的值对于
mode
参数用于
spawn*
family of functions. These are less portable than those listed above.
P_DETACH
类似于
P_NOWAIT
, but the new process is detached from the console of the calling process. If
P_OVERLAY
is used, the current process will be replaced; the
spawn*()
函数不会返回。
可用性:Windows。
New in version 1.6.
os.
startfile
(
path
[
,
operation
]
)
¶
采用关联应用程序启动文件。
当
operation
未指定或
'open'
,这的举动像在 Windows 资源管理器中双击文件,或将文件名作为自变量赋予
start
命令从交互命令 Shell:采用其扩展名关联的任何应用程序 (若有的话) 打开文件。
当另一
operation
有给定,它必须是指定应该对文件做什么的命令动词。由 Microsoft 文档化的常见动词包括
'print'
and
'edit'
(用于文件) 及
'explore'
and
'find'
(用于目录)。
startfile()
尽快返回,一旦发起关联应用程序。没有等待应用程序关闭的选项,也没有检索应用程序退出状态的办法。
path
参数相对于当前目录。若想要使用绝对路径,确保第一个字符不是斜杠 (
'/'
);底层 Win32
ShellExecute()
函数不工作,若它是的话。使用
os.path.normpath()
函数以确保是 Win32 正确编码路径。
可用性:Windows。
2.0 版新增。
New in version 2.5: The operation 参数。
os.
system
(
命令
)
¶
在子 Shell 执行命令 (字符串)。这的实现是通过调用标准 C 函数
system()
,且拥有相同局限性。更改
sys.stdin
, etc. are not reflected in the environment of the executed command.
在 Unix,返回值是进程的退出状态,指定编码格式为
wait()
. Note that POSIX does not specify the meaning of the return value of the C
system()
function, so the return value of the Python function is system-dependent.
在 Windows,返回值是由系统 Shell 所返回的值后于运行
命令
, given by the Windows environment variable
COMSPEC
: on
command.com
systems (Windows 95, 98 and ME) this is always
0
; 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
替换较旧函数采用 subprocess 模块
section in the
subprocess
documentation for some helpful recipes.
可用性: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.
可用性: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.
可用性:Unix。
os.
waitpid
(
pid
,
选项
)
¶
The details of this function differ on Unix and Windows.
On Unix: Wait for completion of a child process given by process id
pid
, and return a tuple containing its process id and exit status indication (encoded as for
wait()
). The semantics of the call are affected by the value of the integer
选项
, which should be
0
for normal operation.
若
pid
大于
0
,
waitpid()
requests status information for that specific process. If
pid
is
0
, the request is for the status of any child in the process group of the current process. If
pid
is
-1
, the request pertains to any child of the current process. If
pid
小于
-1
, status is requested for any process in the process group
-pid
(the absolute value of
pid
).
An
OSError
is raised with the value of errno when the syscall returns -1.
On Windows: Wait for completion of a process given by process handle
pid
, and return a tuple containing
pid
, and its exit status shifted left by 8 bits (shifting makes cross-platform use of the function easier). A
pid
less than or equal to
0
has no special meaning on Windows, and raises an exception. The value of integer
选项
不起作用。
pid
can refer to any process whose id is known, not necessarily a child process. The
spawn*
functions called with
P_NOWAIT
return suitable process handles.
os.
wait3
(
选项
)
¶
类似于
waitpid()
, except no process id argument is given and a 3-element tuple containing the child’s process id, exit status indication, and resource usage information is returned. Refer to
resource
.
getrusage()
for details on resource usage information. The option argument is the same as that provided to
waitpid()
and
wait4()
.
可用性:Unix。
2.5 版新增。
os.
wait4
(
pid
,
选项
)
¶
类似于
waitpid()
, except a 3-element tuple, containing the child’s process id, exit status indication, and resource usage information is returned. Refer to
resource
.
getrusage()
for details on resource usage information. The arguments to
wait4()
are the same as those provided to
waitpid()
.
可用性:Unix。
2.5 版新增。
os.
WNOHANG
¶
The option for
waitpid()
to return immediately if no child process status is available immediately. The function returns
(0, 0)
在此情况下。
可用性:Unix。
os.
WCONTINUED
¶
This option causes child processes to be reported if they have been continued from a job control stop since their status was last reported.
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.
可用性:Unix。
2.3 版新增。
The following functions take a process status code as returned by
system()
,
wait()
,或
waitpid()
as a parameter. They may be used to determine the disposition of a process.
os.
WCOREDUMP
(
status
)
¶
返回
True
if a core dump was generated for the process, otherwise return
False
.
可用性:Unix。
2.3 版新增。
os.
WIFCONTINUED
(
status
)
¶
返回
True
if the process has been continued from a job control stop, otherwise return
False
.
可用性:Unix。
2.3 版新增。
os.
WIFSTOPPED
(
status
)
¶
返回
True
若进程已停止,否则返回
False
.
可用性:Unix。
os.
WIFSIGNALED
(
status
)
¶
返回
True
如果进程由于信号而退出,否则返回
False
.
可用性:Unix。
os.
WIFEXITED
(
status
)
¶
返回
True
若退出进程使用
exit(2)
系统调用,否则返回
False
.
可用性:Unix。
os.
WEXITSTATUS
(
status
)
¶
若
WIFEXITED(status)
is true, return the integer parameter to the
exit(2)
system call. Otherwise, the return value is meaningless.
可用性:Unix。
os.
WSTOPSIG
(
status
)
¶
Return the signal which caused the process to stop.
可用性:Unix。
os.
WTERMSIG
(
status
)
¶
Return the signal which caused the process to exit.
可用性:Unix。
os.
confstr
(
名称
)
¶
Return string-valued system configuration values.
name
specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the
confstr_names
dictionary. For configuration variables not included in that mapping, passing an integer for
name
is also accepted.
若配置值的指定通过
name
未定义,
None
被返回。
若
name
是字符串且未知,
ValueError
被引发。若特定值对于
name
主机系统不支持,即使包括在
confstr_names
,
OSError
被引发采用
errno.EINVAL
对于错误编号。
可用性:Unix
os.
confstr_names
¶
字典映射的名称接受通过
confstr()
to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.
可用性:Unix。
os.
sysconf
(
名称
)
¶
Return integer-valued system configuration values. If the configuration value specified by
name
未定义,
-1
is returned. The comments regarding the
name
parameter for
confstr()
apply here as well; the dictionary that provides information on the known names is given by
sysconf_names
.
可用性:Unix。
os.
sysconf_names
¶
字典映射的名称接受通过
sysconf()
to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system.
可用性:Unix。
下列数据值用于支持路径操纵操作。所有平台都有定义这些。
路径名的高级操作的定义在
os.path
模块。
os.
curdir
¶
The constant string used by the operating system to refer to the current directory. This is
'.'
for Windows and POSIX. Also available via
os.path
.
os.
pardir
¶
The constant string used by the operating system to refer to the parent directory. This is
'..'
for Windows and POSIX. Also available via
os.path
.
os.
sep
¶
The character used by the operating system to separate pathname components. This is
'/'
for POSIX and
'\\'
for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use
os.path.split()
and
os.path.join()
— but it is occasionally useful. Also available via
os.path
.
os.
extsep
¶
The character which separates the base filename from the extension; for example, the
'.'
in
os.py
. Also available via
os.path
.
2.2 版新增。
os.
pathsep
¶
The character conventionally used by the operating system to separate search path components (as in
PATH
),譬如
':'
for POSIX or
';'
为 Windows。也可用凭借
os.path
.
os.
defpath
¶
The default search path used by
exec*p*
and
spawn*p*
if the environment doesn’t have a
'PATH'
key. Also available via
os.path
.
os.
linesep
¶
The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as
'\n'
for POSIX, or multiple characters, for example,
'\r\n'
for Windows. Do not use
os.linesep
as a line terminator when writing files opened in text mode (the default); use a single
'\n'
代替,在所有平台。
os.
urandom
(
n
)
¶
Return a string of n random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a UNIX-like system this will query
/dev/urandom
, and on Windows it will use
CryptGenRandom()
. If a randomness source is not found,
NotImplementedError
会被引发。
For an easy-to-use interface to the random number generator provided by your platform, please see
random.SystemRandom
.
2.4 版新增。