Python:从以非零exit cod退出的命令行获取输出

2024-09-28 06:12:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我最初使用subprocess.check_output,并捕获以非零退出状态出现的被调用进程错误,但是当返回代码存储在错误中时,没有输出显示出这一点。

对输出为0但退出状态为0的情况运行此命令可以正常工作,我可以使用subprocess.check_output获取输出。

我的假设是输出被写入STDOUT,但异常从STDERR中提取其“output”。我试图重新实现check_output的功能,但是当我认为应该看到输出到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 

这给了我变量输出中的以下内容:[('', None)]

我的subprocess.Popen代码正确吗?


Tags: 代码命令output进程windows状态check错误
3条回答

这里有个问题可能会打击到你- http://bugs.python.org/issue9905

你的代码运行良好。结果发现,您调用的进程可能正在输出到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

遗憾的是,我不知道如何解决这个问题。注意,subprocess.check_output结果只包含stdout的输出。check_输出替换将同时输出stderr和stdout。

在检查subprocess.check_output之后,它确实生成了一个只包含stdout的输出的CalledProcessError。

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

To also capture standard error in the result, use 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

相关问题 更多 >

    热门问题