如果成功则获取stdout,如果失败则获取stdout + stderr

时间:2014-09-01 05:50:25

标签: python python-3.x

try:
    output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as exc:
    logger.error('There was an error while ...: \n%s',
                 exc.output)
    raise

执行以下操作的最简单方法是什么:

  1. 使用subprocess模块调用流程。
  2. 如果程序正常退出,请将output变量放入其标准输出。
  3. 如果程序异常退出,请获取其标准输出错误。

1 个答案:

答案 0 :(得分:0)

import subprocess

process= subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait() #wait for the command to finish
output= process.stdout.read()
if process.poll(): #check the error code
    error= process.stderr.read()
相关问题