【问题标题】:Python, handle exceptions caused by file ran by other file in the other file?Python,处理由其他文件中的其他文件运行的文件引起的异常?
【发布时间】: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。

标签: python exception


【解决方案1】:

尝试subprocesscheck=True 选项:

来自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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2019-04-18
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 2020-02-03
    相关资源
    最近更新 更多