我阅读了子流程 – 调用,check_call,check_output提供的功能,并了解每个功能的作用和不同之处。我正在使用check_output,所以我可以访问stdout,并使用“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(如果它被发送到粗壮,可以),并访问退出代码。我可以手动检查基于退出代码的通过/失败,除了被抛出的异常。
谢谢,
艾哈迈德。
尝试这个版本:
try:
cmnd_output = check_output(cmnd, stderr=STDOUT, shell=True, timeout=3, universal_newlines=True);
except CalledProcessError as exc:
print("Status : FAIL", exc.returncode, exc.output)
else:
print("Output: \n{}\n".format(cmnd_output))
这样,只有在呼叫成功的情况下,才能打印输出。
在CalledProcessError
的情况下,打印返回码和输出。
http://stackoverflow.com/questions/16198546/get-exit-code-and-stderr-from-subprocess-call
本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 从子进程调用获取退出代码和stderr