我阅读了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就可以了)并获得退出代码.我可以根据退出代码手动判断通过/失败,而不通过异常.
非常感谢.