子流程错误处理滑倒
我一直在这一点上停留。基本上我遵循了一些子进程使用示例,但我想我还有其他一些问题。子流程错误处理滑倒
我正在编写一个脚本,通过一个电影文件目录运行并运行exiftool
每个人都拉出一些关于他们的信息。
我可以使它工作,直到我遇到一个exiftool
错误的情况。如Error: File format error
...所以我试图捕捉那个或任何错误,即exiftool
生成(即使错误消息可以很方便地作为变量),并跳过该文件。
在下面的代码中,myArg
只是该文件的路径。
try: proc = subprocess.Popen(["exiftool", "-s", "-ImageWidth", "-ImageHeight", "-VideoFrameRate", "-CompressorName", "-MediaDuration", myArg], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
except OSError:
print "Pass, something is borked..."
pass
回答:
我想你要寻找的是从exiftool
获得的退出代码。它应该成功返回0,因此检查您可以在proc.communicate()
之后添加这样的错误:
if proc.returncode != 0: print "Pass, something is borked..."
如果错误讯息,到标准输出,你应该在你的out
变量。如果它转到stderr,请将stderr=subprocess.PIPE
添加到您的pOpen命令中,然后它应该在err
中。
回答:
如果我理解正确,您想传递的,而不是OSERROR的同时阅读文件,如果是的话那么广义的错误处理,可以发生任何错误,
except Exception as e: print "Error Descr"+ str(e)
pass
回答:
有很多方法可以做到这一点。你可以使用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
以上是 子流程错误处理滑倒 的全部内容, 来源链接: utcz.com/qa/262520.html