“子进程.Popen"- 检查成功和错误

2022-01-18 00:00:00 python python-3.x subprocess stdout stderr

问题描述

我想检查一个子进程是成功完成还是失败了.目前我已经提出了一个解决方案,但我不确定它是否正确和可靠.是否保证每个进程仅将其错误输出到 stderr 尊重 stdout:

I want to check if a subprocess has finished execution successfully or failed. Currently I have come up with a solution but I am not sure if it is correct and reliable. Is it guaranteed that every process outputs its errors only to stderr respectfully to stdout:

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

Note: I am not interested in just redirecting/printing out the output. That I know already how to do.

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


解决方案

你需要对进程的输出做些什么吗?

Do you need to do anything with the output of the process?

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

The check_call method might be useful here. See the python docs here: https://docs.python.org/2/library/subprocess.html#subprocess.check_call

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

You can then use this as follows:

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

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

However, this relies on command returning an exit code of 0 for succesful completion and a non-zero value for an error.

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

If you need to capture the output as well, then the check_output method may be more appropriate. It is still possible to redirect the standard error if you need this as well.

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

相关文章