Python,在另一个文件中处理文件运行引起的异常?

Python, handle exceptions caused by file ran by other file in the other file?

我正在制作一个运行另一个文件 (B) 的 python 程序 (A)。如果 B 以代码 0 退出,则 A 也退出。但是,如果 B 崩溃了,我想在 A 中自己处理那个异常。

父/主文件(A)出现异常 that asks the same thing, however, the one asking only needs the exit code or the error message printed to stderr. However, i want the raw data otherwise provided by sys.exc_info

使用 check=True 选项尝试 subprocess

来自subprocess docs

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.

如果 B.py 类似于:

print("HELLO from B")
raise Exception("MEH")

那么 A.py 可能是这样的:

import subprocess

try:
    print("TRYING B.py")
    subprocess.run(["python", "B.py"], check=True)
except subprocess.CalledProcessError as cpe:
    print("OH WELL: Handling exception from B.py")
    print(f"Exception from B: {cpe}")

结果:

~ > python A.py
TRYING B.py
HELLO from B
Traceback (most recent call last):
  File "B.py", line 2, in <module>
    raise Exception("MEH")
Exception: MEH
OH WELL: Handling exception from B.py
Exception from B: Command '['python', 'B.py']' returned non-zero exit status 1.

要使异常不显示,请将 B.py 更改为以下内容:

import os
import sys
sys.stderr = open(os.devnull, 'w')
print("HELLO from B")
raise Exception("MEH")

结果:

~ > python A.py
TRYING B.py
HELLO from B
OH WELL: Handling exception from B.py
Exception from B: Command '['python', 'B.py']' returned non-zero exit status 1.