我阅读了子流程调用、 check _ call、 check _ output 提供的函数,并了解了每个函数的工作原理以及它们之间的功能差异。我当前使用 check _ output,因此可以访问标准输出,并使用“ 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 _ output”没有初始化,也不能访问 stderr,并且我得到以下错误消息:
print("Output: \n{}\n".format(cmnd_output))
UnboundLocalError: local variable 'cmnd_output' referenced before assignment
我认为这是因为异常导致“ check _ output”立即停止运行,而不需要在 try 块中进行任何进一步的处理,也就是赋值给“ cmnd _ output”。如果我说错了,请纠正我。
有没有什么方法可以让我访问 stderr (如果发送到 stout 就可以了)并且访问退出代码。我可以手动检查通过/失败的基础上退出代码没有抛出异常。
谢谢, 艾哈迈德。