我通读了子流程提供的功能-调用,检查_调用,检查_输出,并了解它们各自的工作原理以及功能上的不同。我当前正在使用check_output,因此我可以访问stdout,并使用“ try块”来捕获异常,如下所示:
# "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
我认为那是因为异常导致try块中的“ check_output”立即保释,而没有进行任何进一步的处理,即“ cmnd_output”。如果我错了,请纠正我。
有什么办法可以访问stderr(如果将其发送到stout,可以)并可以访问退出代码。我可以根据退出代码手动检查通过/失败,而不会引发异常。
谢谢,艾哈迈德。
ret = subprocess.check_output(cmd , stderr=STDOUT,shell=True)NameError: global name 'STDOUT' is not defined