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

我想检查子进程是否已成功执行或失败.目前我已经提出了一个解决方案,但我不确定它是否正确可靠.是否保证每个进程仅将stdr的错误输出到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

解决方法:

您是否需要对流程的输出执行任何操作?

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

但是,这依赖于命令返回退出代码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

上一篇:如何play billard


下一篇:Linux Bash shell脚本中的IO重定向无法重新创建已移动/已删除的文件?