Python:从带有非零退出代码的命令行获取输出

Python:从带有非零退出代码的命令行获取输出,python,subprocess,stdout,windows-server-2008-r2,stderr,Python,Subprocess,Stdout,Windows Server 2008 R2,Stderr,我正在Windows Server 2008 R2 x64设备上使用Python 2.7.1 我试图得到一个命令行进程的输出,它在输出我需要的信息后给出一个非零的退出状态 我最初使用的是子流程。检查\u output,并捕获在退出状态为非零的情况下发生的被调用进程错误,但当返回代码存储在错误中时,没有输出显示这一点 针对提供输出但退出状态为0的情况运行此命令可以正常工作,并且我可以使用subprocess.check_output获得输出 我的假设是,输出正在写入STDOUT,但异常从STDER

我正在Windows Server 2008 R2 x64设备上使用Python 2.7.1

我试图得到一个命令行进程的输出,它在输出我需要的信息后给出一个非零的退出状态

我最初使用的是
子流程。检查\u output
,并捕获在退出状态为非零的情况下发生的被调用进程错误,但当返回代码存储在错误中时,没有输出显示这一点

针对提供输出但退出状态为0的情况运行此命令可以正常工作,并且我可以使用subprocess.check_output获得输出

我的假设是,输出正在写入STDOUT,但异常从STDERR提取其“输出”。我试图重新实现check_输出的功能,但是当我认为应该看到STDOUT和STDERR的输出时,我仍然没有得到任何输出。我当前的代码如下(其中“command”是我正在运行的命令的全文,包括参数):

process = subprocess.Popen(command, stdout=subprocess.PIPE, 
stderr=subprocess.STDOUT, universal_newlines=True)
output = process.communicate()
retcode = process.poll()
if retcode:
    raise subprocess.CalledProcessError(retcode, image_check, output=output)
    return output 
这在变量输出中提供了以下内容:
[('',无)]


我的
子流程.Popen
代码正确吗?

这里有一个问题可能会影响您-

您的代码工作正常。结果表明,您正在调用的进程可能正在输出到CON。请参见以下示例

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
输出

subprocess -> 
native -> ('', None)
stderr subproces CalledProcessError.output = stdout
native CalledProcessError.output = stderr stdout
遗憾的是,我不知道如何解决这个问题。请注意,
子流程.check\u output
结果只包含来自stdout的输出。您的check\u输出替换将同时输出stderr和stdout


检查
子流程。检查输出后,它确实会生成一个被调用的流程错误,其输出仅包含stdout。

您是否尝试过python文档页面中提到的
stderr=subprocess.stdout

要同时捕获结果中的标准错误,请使用 stderr=subprocess.STDOUT:

下面是一个测试代码:

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
输出:

errrrr
e.output:  
e.output:  errrrr

我很确定这就是它的发展方向。我与供应商取得了联系,发现了一些额外的未记录的参数,这些参数阻止了非零退出状态的发生,因此我的脚本现在可以工作了,尽管我仍然想知道如何在
之后从CON.communicate()捕获输出
,您可以直接使用
process.returncode
而不是
process.poll()
。如何使用Python从命令行获取输出: