Python: get output from a command line which exits with nonzero exit code

后端 未结 3 2102
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 04:42

I am Using Python 2.7.1 on a Windows Server 2008 R2 x64 box.

I\'m trying to get the output of a command line process which gives a nonzero exit status after

3条回答
  •  旧巷少年郎
    2021-02-09 04:56

    Have you tried stderr=subprocess.STDOUT as mentioned in the python doc page:

    To also capture standard error in the result, use stderr=subprocess.STDOUT:

    Here is a test code:

    import subprocess
    
    try:
        subprocess.check_output('>&2 echo "errrrr"; exit 1', shell=True)
    except subprocess.CalledProcessError as e:
        print 'e.output: ', e.output
    
    
    try:
        subprocess.check_output('>&2 echo "errrrr"; exit 1', shell=True, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        print 'e.output: ', e.output
    

    output:

    errrrr
    e.output:  
    e.output:  errrrr
    

提交回复
热议问题