我想使用上下文管理器不仅捕获一个异常,就像在this answer中那样,而是捕获任意数量的系列异常,以便以下代码将执行自定义代码来处理
ModuleNotFoundError
三次:
with handle_ModuleNotFoundErrors():
import this_is_not_installed
import neither_is_this
import none_of_these_are_installed
到目前为止,我有以下代码,但它只会处理第一个
ModuleNotFoundError
:
from contextlib import contextmanager
import re
@contextmanager
def handle_ModuleNotFoundErrors():
try:
yield
except ModuleNotFoundError as e:
failed_module = re.search(r"'((?:\\'|[^'])+)'", e.msg).group(1)
print(f'Handling {failed_module}...')