有很多方法可以做到這一點。你可以使用subprocess.call
如果你只是想返回代碼:
import subprocess
ret = subprocess.call(['ls', 'sadknlsknfd'])
if ret:
print('Something is borked\nreturncode:%i' % ret)
# Something is borked
# returncode:2
或者subprocess.check_call
引發異常:
try:
subprocess.check_call(['ls', 'sadknlsknfd'])
except subprocess.CalledProcessError as e:
print('Something is borked\ncommand: %s\noutput: %s\nreturncode:%i'
% (e.cmd, e.output, e.returncode))
# Something is borked
# command: ['ls', 'sadknlsknfd']
# output: None
# returncode:2
或者,如果你想要的輸出,以及你可以使用subprocess.check_output
:
try:
# note that `out` will be undefined if the call fails
out = subprocess.check_output(['ls', 'sadknlsknfd'])
except subprocess.CalledProcessError as e:
print('Something is borked\ncommand: %s\noutput: %s\nreturncode:%i'
% (e.cmd, e.output, e.returncode))
# Something is borked
# command: ['ls', 'sadknlsknfd']
# output:
# returncode:2
要獲得STDERR消息,您也可以使用redirect it to STDOUT:
try:
out = subprocess.check_output(['ls', 'sadknlsknfd'], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
# `out` will be undefined if the call fails
print('Something is borked\ncommand: %s\noutput: %s\nreturncode:%i'
% (e.cmd, e.output, e.returncode))
# Something is borked
# command: ['ls', 'sadknlsknfd']
# output: ls: cannot access sadknlsknfd: No such file or directory
# returncode:2
您也可以使用subprocess.Popen.communicate
這樣的:
p = subprocess.Popen(['ls', 'saddsfsdf'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
ret = p.returncode
if ret:
print('Something is borked\nstdout:%s\nstderr:%s\nretcode:%i'
% (out, err, ret))
# Something is borked
# stdout:
# stderr:ls: cannot access saddsfsdf: No such file or directory
# retcode:2
這工作,也幫助看到我做錯了什麼。 – user1978912