Python 3不再推荐使用老的os.system()、os.popen()、commands.getstatusoutput()等方法来调用系统命令,而建议统一使用subprocess库所对应的方法如:Popen()、getstatusoutput()、call()。
推荐并记录一些常用的使用范例:
# 标准用法使用数据传参,可以用shlex库来正确切割命令字符串
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output \"spam spam.txt\" -cmd \"echo \'$MONEY\'\"
>>> args = shlex.split(command_line)
>>> print(args)
[\'/bin/vikings\', \'-input\', \'eggs.txt\', \'-output\', \'spam spam.txt\', \'-cmd\', \"echo \'$MONEY\'\"]
>>> p = subprocess.Popen(args) # Success!
import subprocess
try:
proc = subprocess.Popen([`ls`, `-a`, `/`], stdout=subprocess.PIPE)
print(proc.stdout.read())
except:
print(\"error when run `ls` command\")
# 使用with语句替代try-except-finally
with Popen([\"ifconfig\"], stdout=PIPE) as proc:
log.write(proc.stdout.read())
# Windows下由于Windows API的CreateProcess()入参为字符串,
# Popen需要把输入的数组拼接为字符串。因此建议直接传入字符串参数。
p = subprocess.Popen(\'D:\\\\Tools\\\\Git\\\\git-bash.exe --cd=\"D:\\\\Codes\"\', stdout=subprocess.PIPE)
print(p.stdout.read())
import subprocess
try:
retcode = subprocess.call(\"mycmd\" + \" myarg\", shell=True)
if retcode < 0:
print(\"Child was terminated by signal\", -retcode, file=sys.stderr)
else:
print(\"Child returned\", retcode, file=sys.stderr)
except OSError as e:
print(\"Execution failed:\", e, file=sys.stderr)
>>> subprocess.getstatusoutput(\'ls /bin/ls\')
(0, \'/bin/ls\')
>>> subprocess.getoutput(\'ls /bin/ls\')
\'/bin/ls\'
详细可以查阅Python 3官方文档:
os: https://docs.python.org/3/library/os.htm…
subprocess: https://docs.python.org/3/library/subpro…