“subprocess.Popen” - 检查成功和错误

新手上路,请多包涵

我想检查子流程是成功执行还是失败。目前我想出了一个解决方案,但我不确定它是否正确可靠。是否保证每个进程仅将其错误输出到 stderr 恭敬地 stdout

注意:我对重定向/打印输出不感兴趣。我已经知道该怎么做了。

 pipe = subprocess.Popen(command,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                universal_newlines=True)

if "" == pipe.stdout.readline():
    print("Success")
    self.isCommandExectutionSuccessful = True

if not "" == pipe.stderr.readline():
    print("Error")
    self.isCommandExectutionSuccessful = True

或者:

    if "" == pipe.stdout.readline():
       print("Success")
       self.isCommandExectutionSuccessful = True
   else:
       print("Error")
       self.isCommandExectutionSuccessful = False

和:

    if not "" == pipe.stderr.readline():
       print("Success")
       self.isCommandExectutionSuccessful = True
   else:
       print("Error")
       self.isCommandExectutionSuccessful = False

原文由 Zingam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

您需要对过程的输出做些什么吗?

check_call 方法在这里可能会有用。请在此处查看 python 文档: https ://docs.python.org/2/library/subprocess.html#subprocess.check_call

然后您可以按如下方式使用它:

 try:
  subprocess.check_call(command)
except subprocess.CalledProcessError:
  # There was an error - command exited with non-zero code

但是,这依赖于 command 成功完成返回退出代码 0,错误返回非零值。

如果您还需要捕获输出,那么 check_output 方法可能更合适。如果您也需要,仍然可以重定向标准错误。

 try:
  proc = subprocess.check_output(command, stderr=subprocess.STDOUT)
  # do something with output
except subprocess.CalledProcessError:
  # There was an error - command exited with non-zero code

请参阅此处的文档: https ://docs.python.org/2/library/subprocess.html#subprocess.check_output

原文由 elParaguayo 发布,翻译遵循 CC BY-SA 3.0 许可协议

检查返回码、stdout 和 stderr 的完整解决方案:

 import subprocess as sp

# ok
pipe = sp.Popen( 'ls /bin', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
# res = tuple (stdout, stderr)
res = pipe.communicate()
print("retcode =", pipe.returncode)
print("res =", res)
print("stderr =", res[1])
for line in res[0].decode(encoding='utf-8').split('\n'):
  print(line)

# with error
pipe = sp.Popen( 'ls /bing', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
res = pipe.communicate()
print("retcode =", pipe.returncode)
print("res =", res)
print("stderr =", res[1])

印刷:

 retcode = 0
res = (b'bash\nbunzip2\nbusybox\nbzcat\n...zmore\nznew\n', b'')
stderr = b''
bash
bunzip2
busybox
bzcat
...
zmore
znew

retcode = 2
res = (b'', b"ls: cannot access '/bing': No such file or directory\n")
stderr = b"ls: cannot access '/bing': No such file or directory\n"

原文由 PJ_Finnegan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题