【发布时间】:2021-08-02 21:39:40
【问题描述】:
我正在制作一个运行另一个文件 (B) 的 python 程序 (A)。如果 B 以代码 0 退出,则 A 也退出。但是,如果 B 崩溃,我想自己在 A 中处理该异常。
有this question 询问同样的事情,但是,询问的人只需要退出代码或打印到stderr 的错误消息。但是,如果父/主文件 (A) 中发生异常,我想要 sys.exc_info 提供的原始数据。
【问题讨论】:
-
您考虑过使用subprocess 模块吗?
-
@alfinkel24 我想要,但是 python 自己处理异常而不是 A 来处理它。因此,我无法处理 A 中的异常。如果有任何方法可以使用子进程处理 A 中的异常,请告诉我,我只尝试过 subproces.run("python", B)
-
您是否尝试过使用
check=True选项?来自文档:If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.。如subprocess.run("python", B, check=True)。 -
@alfinkel24 它有效,谢谢。 Python 仍然打印堆栈跟踪,有什么方法可以阻止它吗?我想自己打印。
-
您可以在 B.py 中将 STDERR 重定向到 /dev/null。参考:stackoverflow.com/questions/6735917/… 的公认答案,但不是 sys.stdout 你会设置 sys.stderr。