我阅读了subprocess提供的函数——call、check_call、check_output,并了解它们是如何工作的,以及它们在功能上的差异.我目前正在使用check_输出,因此我可以访问标准输出,并使用"try block"捕获异常,如下所示:

# "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_输出"未初始化且无法访问stderr,我收到以下错误消息:

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

我认为这是因为异常会导致"check_output"立即跳转,而不进行任何进一步的处理,也就是在try块中分配给"cmnd_output".如果我错了,请纠正我.

我有没有办法访问stderr(如果发送给stout就可以了)并获得退出代码.我可以根据退出代码手动判断通过/失败,而不通过异常.

非常感谢.

推荐答案

试试这个版本:

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))

这样,只有在调用成功时,才能打印输出.

Python-3.x相关问答推荐

根据其他数据框架的列顺序从数据框架中进行 Select

"安装serial vs安装psyserial header,"""

如何将CSV或FDF数据解析到Python词典并注入到模板PDF表单中?

在多个测试中维护和报告变量

如何使用PySide6创建切换框架?

在Python中从列创建新行

Django 3.2/Django-cms 3.11:查找错误:型号帐户.客户用户未注册

当索引大于一个整数而小于前一个索引时,我如何返回列值?

ValueError at /register/ 视图authenticate.views.register_user 未返回HttpResponse 对象.它返回 None 相反

继承自 Counter 与 dict 的类实例的 Deepcopy

替换 .txt 文件中的项目列表

一起使用数据类和枚举

将自动文本转换为 DataFrame

使用 python 查找标记的元素

判断 gekko 中的表达式

如何将虚拟变量列转换为多列?

使用带有多线程的 win32com

python asyncio - 如何等待取消的屏蔽任务?

通过多个键对字典列表进行分组和聚合

命名参数可以与 Python 枚举一起使用吗?