我正在使用
subprocess
模块和 check_output()
在我的 Python 脚本中创建一个虚拟 shell,它对于返回零退出状态的命令运行良好,但是对于不返回零退出状态的命令,它会返回异常而不打印在正常 shell 的输出中会显示的错误。
例如,我希望有这样的工作:
>>> shell('cat non-existing-file')
cat: non-existing-file: No such file or directory
但是,却发生了这种情况:
>>> shell('cat non-existing-file')
CalledProcessError: Command 'cat non-existing-file' returned non-zero exit status 1 (file "/usr/lib/python2.7/subprocess.py", line 544, in check_output)
即使我可以使用
try
和 except
删除 Python 异常消息,我仍然希望 cat: non-existing-file: No such file or directory
显示给用户。
我该怎么做?
shell()
:
def shell(command):
output = subprocess.check_output(command, shell=True)
finished = output.split('\n')
for line in finished:
print line
return
也许是这样的?
def shell(command):
try:
output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
except Exception, e:
output = str(e.output)
finished = output.split('\n')
for line in finished:
print line
return
如果您使用的是 Python 3.5+,则可以使用
check=False
: 运行它
subprocess.run("exit 1", shell=True, check=False)
如果检查为 true,并且进程以非零退出代码退出,则会引发 CalledProcessError 异常。该异常的属性包含参数、退出代码以及 stdout 和 stderr(如果捕获了它们)。
对于较旧的 Python 3 版本,有不同的方法来检查和不检查调用。
要获取输出,只需传递
capture_output=True
,然后从 stdout
获取
CompletedProcess
值
使用怎么样
subprocess.run()
import subprocess
output = subprocess.run(['cat', 'non-existing-file'], stdout = subprocess.PIPE, stderr=subprocess.PIPE)
print (output.stderr.decode())
这是输出
> python3 file.py
cat: non-existing-file: No such file or directory