On this page
36.16. 命令-运行命令的 Util
从 2.6 版开始不推荐使用:Python 3 中已删除commands模块。请改用subprocess模块。
commands模块包含os.popen()的包装函数,这些包装函数将系统命令作为字符串,并返回该命令生成的任何输出以及(可选)退出状态。
subprocess模块提供了更强大的Function来生成新流程并检索其结果。使用subprocess模块比使用commands模块更好。
Note
在 Python 3.x 中,已删除getstatus()和两个未记录的函数(mk2arg()
和mkarg()
)。同样,getstatusoutput()和getoutput()已移至subprocess模块。
commands模块定义以下Function:
commands.
getstatusoutput
(* cmd *)- 在具有os.popen()的 shell 中执行字符串* cmd *并返回 2Tuples
(status, output)
。 * cmd *实际上以{ cmd ; } 2>&1
的身份运行,因此返回的输出将包含输出或错误消息。从输出中删除尾随换行符。可以根据 C 函数wait()
的规则解释命令的退出状态。
- 在具有os.popen()的 shell 中执行字符串* cmd *并返回 2Tuples
commands.
getoutput
(* cmd *)- 类似于getstatusoutput(),除了退出状态被忽略,返回值是包含命令输出的字符串。
commands.
getstatus
(* file *)- 以字符串形式返回
ls -ld file
的输出。此函数使用getoutput()函数,并在参数中正确转义反斜杠和美元符号。
- 以字符串形式返回
从 2.6 版开始不推荐使用:此Function不明显且无用。在getstatusoutput()的情况下,该名称也具有误导性。
Example:
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
See also
Module subprocess
用于产生和 Management 子流程的模块。