"subprocess.Popen" - 检查成功和错误

Zin*_*gam 25 python subprocess stdout stderr python-3.x

我想检查子进程是否已成功执行或失败.目前我已经提出了一个解决方案,但我不确定它是否正确可靠.是否保证每个进程仅向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
Run Code Online (Sandbox Code Playgroud)

或者:

   if "" == pipe.stdout.readline():
       print("Success")
       self.isCommandExectutionSuccessful = True
   else:
       print("Error")
       self.isCommandExectutionSuccessful = False
Run Code Online (Sandbox Code Playgroud)

和:

   if not "" == pipe.stderr.readline():
       print("Success")
       self.isCommandExectutionSuccessful = True
   else:
       print("Error")
       self.isCommandExectutionSuccessful = False
Run Code Online (Sandbox Code Playgroud)

elP*_*ayo 24

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

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
Run Code Online (Sandbox Code Playgroud)

但是,这依赖于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
Run Code Online (Sandbox Code Playgroud)

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

  • 好。还有`check_output`方法。您可以从其中获取stdout和stderr,但仍会捕获错误。参见此处:https://docs.python.org/2/library/subprocess.html#subprocess.check_output (2认同)

PJ_*_*gan 16

检查返回码、标准输出和标准错误的完整解决方案:

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])
Run Code Online (Sandbox Code Playgroud)

印刷:

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"
Run Code Online (Sandbox Code Playgroud)