ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-09-23 04:08:08  阅读:488  来源: 互联网

标签:python python-3-x subprocess stderr stdout


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

标签:python,python-3-x,subprocess,stderr,stdout
来源: https://codeday.me/bug/20190923/1813751.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有