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

后端 未结 3 2085
没有蜡笔的小新
没有蜡笔的小新 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 05:07

    You code works fine. Turns out that the process that you are calling is probably outputing to CON. See the following example

    import subprocess
    
    def check_output(command):
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
        output = process.communicate()
        retcode = process.poll()
        if retcode:
                raise subprocess.CalledProcessError(retcode, command, output=output[0])
        return output 
    
    command = "echo this>CON"
    
    print "subprocess -> " + subprocess.check_output(command, shell=True)
    print "native -> " + str(check_output(command))
    
    try:
        subprocess.check_output("python output.py", shell=True)
    except subprocess.CalledProcessError, e:
        print "subproces CalledProcessError.output = " + e.output
    
    try:
        check_output("python output.py")
    except subprocess.CalledProcessError, e:
        print "native CalledProcessError.output = " + e.output
    

    Output

    subprocess -> 
    native -> ('', None)
    stderr subproces CalledProcessError.output = stdout
    native CalledProcessError.output = stderr stdout
    

    Sadly, I do not know how to resolve the issue. Notice that subprocess.check_output results contains only the output from stdout. Your check_output replacement would output both stderr and stdout.

    After inspecting subprocess.check_output, it does indeed generate a CalledProcessError with the output containing only stdout.

提交回复
热议问题