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

2024-09-28 22:29:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: selftruereadlineif进程stderrstdoutnot
3条回答

带有check-on返回代码、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"

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

在这里,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

您可以使用check_call()方法检查进程的返回代码。 如果进程返回非零值,则将引发调用进程错误。

相关问题 更多 >