gpt4 book ai didi

python - 从子进程调用中获取退出代码和标准错误

转载 作者:IT老高 更新时间:2023-10-28 20:24:30 26 4
gpt4 key购买 nike

我阅读了 subprocess 提供的函数 - call、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 block 中分配给“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))

这种方式只有在调用成功时才会打印输出。如果是 CalledProcessError你打印返回码和输出。

关于python - 从子进程调用中获取退出代码和标准错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16198546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com