从子进程调用中获取退出代码和 stderr [英] Get exit code and stderr from subprocess call

查看:44
本文介绍了从子进程调用中获取退出代码和 stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 subprocess 提供的函数 - call、check_call、check_output,并了解每个函数的工作原理和彼此的功能不同.我目前正在使用 check_output,因此我可以访问标准输出,并使用try 块"来捕获异常,如下所示:

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 currently using check_output, so I can have access to the stdout, and used "try block" to catch the exception, as follows:

# "cmnd" is a string that contains the command along with it's arguments. 
try:
    cmnd_output = check_output(cmnd, stderr=STDOUT, shell=True, timeout=3, universal_newlines=True);                         
except CalledProcessError:                                                                                                   
    print("Status : FAIL")                                                                                                   
print("Output: \n{}\n".format(cmnd_output))                                                                                  

我遇到的问题是,当抛出异常时,cmnd_output"未初始化且无法访问 stderr,我收到以下错误消息:

The issue I am running into is when an exception is thrown, "cmnd_output" is not initialized and don't have access to stderr, and I get the following error message:

print("Output: \n{}\n".format(cmnd_output))
UnboundLocalError: local variable 'cmnd_output' referenced before assignment

我认为那是因为异常导致check_output"在没有任何进一步处理的情况下立即保释,也就是在 try 块中分配给cmnd_output".如果我错了,请纠正我.

I think thats because the exception causes the "check_output" to bail immediately without any further processing, aka assignment to "cmnd_output", in the try block. Please correct me if I am wrong.

有什么办法可以访问stderr(如果它被发送到stout就可以)并可以访问退出代码.我可以根据退出代码手动检查通过/失败,而不会抛出异常.

Is there any way I can get access to stderr (it's ok if it's sent to stout) and have access to the exit code. I can manually check for pass/fail based on exit code with out the exception being throuwn.

谢谢,艾哈迈德.

推荐答案

试试这个版本:

import subprocess
try:
    output = subprocess.check_output(
        cmnd, stderr=subprocess.STDOUT, shell=True, timeout=3,
        universal_newlines=True)
except subprocess.CalledProcessError as exc:
    print("Status : FAIL", exc.returncode, exc.output)
else:
    print("Output: \n{}\n".format(output))

这样你只会在调用成功时打印输出.如果出现 CalledProcessError 你打印返回码和输出.

This way you will print the output only if the call was successful. In case of a CalledProcessError you print the return code and the output.

这篇关于从子进程调用中获取退出代码和 stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆