我使用子进程来运行脚本。但是那个被调用的脚本本身使用子进程来执行一些命令。问题是,当我在外部脚本中捕获异常时,它只是说调用的脚本中存在错误。
所以,我的问题是如何将错误从内部脚本传播到外部脚本,以便我知道内部脚本中发生的确切原因。
这就是我如何使用子进程捕获异常并在错误时退出。
try:
output = subprocess.check_output(cmd)
except Exception as e:
print(str(e))
sys.exit(1)
最佳答案
如果您使用subprocess
python模块,您可以分别处理命令的STDOUT、STDERR和返回码。您可以查看完整命令调用程序实现的示例。当然,如果您愿意,您可以使用 try.. except
扩展它。
下面的函数返回 STDOUT、STDERR 和返回代码,以便您可以在其他脚本中处理它们。
import subprocess
def command_caller(command=None)
sp = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
out, err = sp.communicate()
if sp.returncode:
print(
"Return code: %(ret_code)s Error message: %(err_msg)s"
% {"ret_code": sp.returncode, "err_msg": err}
)
# You can raise an error if the return code of command is not zero.
# raise Exception(
# "Return code: %(ret_code)s Error message: %(err_msg)s"
# % {"ret_code": sp.returncode, "err_msg": err}
# )
return sp.returncode, out, err
关于python - 子流程内的子流程。如何传播错误输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219578/