滑过子进程错误处理

时间:2015-10-20 11:12:05

标签: python error-handling subprocess

我被困在这一段时间。基本上我已经遵循了一些子流程使用示例,但我想我必须有其他一些问题。

我正在编写一个脚本,该脚本通过一组电影文件运行,并在每个脚本上运行exiftool以获取有关它们的一些信息。

我可以使它工作,直到我遇到exiftool错误的情况。例如Error: File format error ...所以我试图捕获exiftool生成的错误或任何错误(即使错误消息可能很容易作为变量),只是跳过该文件。 / p>

在下面的代码中,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

3 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。如果您只想要返回代码,可以使用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

答案 1 :(得分:1)

我认为你要找的是从exiftool获取退出代码。它应该在成功时返回0,因此要检查错误,您可以在proc.communicate()

之后添加此错误
if proc.returncode != 0:
    print "Pass, something is borked..."

如果错误消息发送到stdout,您应该将其放在out变量中。如果它转到stderr,请将stderr=subprocess.PIPE添加到您的pOpen命令,然后它应该在err

答案 2 :(得分:0)

如果我理解正确你想要传递读取文件时可能发生的任何错误,如果是这样的话,那就是广义错误处理,而不是OsError

except Exception as e:
   print "Error Descr"+ str(e)
   pass