Bri*_*ian 5 python error-handling command-line subprocess return-value
我正在通过Python的子进程模块运行命令行实用程序。我创建带有命令行参数和stdout = subprocess.PIPE的subprocess.Popen()对象,然后使用subprocess.wait()等待任务完成并返回返回代码,该代码应指示任务是否成功完成。
translate = subprocess.Popen(['gdal_translate', '-of', 'HFA', 'inDataset', 'outDataset'], stdout=subprocess.PIPE)
if translate.wait() == 0: print "Success"
else: print "Fail - %s" % translate.stdout.read()
Run Code Online (Sandbox Code Playgroud)
如果我在Windows命令提示符下运行脚本,则可以看到gdal_translate提供的消息,并且他们说有错误导致进程失败,但是我的脚本仍显示“成功”。
如果返回码始终为0,如何检查命令行实用程序报告的错误?
可能会输出错误,并且返回码仍为零。在您的代码中,您仅捕获标准输出,而不捕获标准错误。在下面的运行功能中,它将运行命令,等待执行结束,然后读取返回码标准错误和标准输出。如果标准错误中有任何内容,或者返回码不为零,则将其视为失败。您可以在代码中看到四个示例调用。第一个是正常的成功调用,第二个是返回码0,但有错误输出和标准输出。第三个具有非零返回码和错误输出,而最后一个示例具有非零返回码,根本没有输出。
码
from subprocess import Popen, PIPE
def run(cmd):
print '-'*40
print 'running:', cmd
p = Popen(cmd, stderr=PIPE, stdout=PIPE, shell=True)
output, errors = p.communicate()
print [p.returncode, errors, output]
if p.returncode or errors:
print 'something went wrong...'
run("echo all is well")
run("echo out;echo error 1>&2")
run("this-will-fail")
run("exit 1")
Run Code Online (Sandbox Code Playgroud)
输出
----------------------------------------
running: echo all is well
[0, '', 'all is well\n']
----------------------------------------
running: echo out;echo error 1>&2
[0, 'error\n', 'out\n']
something went wrong...
----------------------------------------
running: this-will-fail
[127, '/bin/sh: this-will-fail: not found\n', '']
something went wrong...
----------------------------------------
running: exit 1
[1, '', '']
something went wrong...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12591 次 |
| 最近记录: |