Get exit code and stderr from subprocess call

后端 未结 5 2214
逝去的感伤
逝去的感伤 2020-12-14 05:07

I read up on the functions provided by subprocess - call, check_call, check_output, and understand how each works and differs in functionality from one another. I am curren

5条回答
  •  臣服心动
    2020-12-14 05:55

    Both of the proposed solutions either mix the stdout/stderr, or use Popen which isn't quite as simple to use as check_output. However, you can accomplish the same thing, and keep stdout/stderr separate, while using check_output if you simply capture stderr by using a pipe:

    import sys
    import subprocess
    
    try:
        subprocess.check_output(cmnd, stderr=subprocess.PIPE)
    except subprocess.CalledProcessError as e:
        print('exit code: {}'.format(e.returncode))
        print('stdout: {}'.format(e.output.decode(sys.getfilesystemencoding())))
        print('stderr: {}'.format(e.stderr.decode(sys.getfilesystemencoding())))
    

    In this example, since we captured stderr, it's available in the exception's stderr attribute (without capturing with the pipe, it would just be None).

提交回复
热议问题