仅导入导致的Catch导入错误

时间:2018-01-14 00:47:50

标签: python error-handling python-import

我的情况是使用importlib模块动态加载python文件。然后我捕获ImportError以检测文件是否不存在。但是,这也会捕获由导入间接导致的任何importerrors。 E.g。

# file a.py
import importlib

try:
    importlib.load_module("b")
except ImportError:
    print("it seems b.py does not exist!")  # oops! it actually does, it just also raised an ImportError!

# file b.py

import nonexistantmoduletocauserror

我希望能够区分由ImportError引起的importlib.load_module和由执行导入模块本身的过程引起的差异。

2 个答案:

答案 0 :(得分:1)

只需创建并使用自定义例外:

档案MyImportError.py

class MyImportError(Exception):
    """Raise for my specific kind of exception"""

档案a.py

from MyImportError import MyImportError
import importlib

try:
    importlib.import_module("b")
except MyImportError:
    print("Error: It seems b.py does not exist!")

档案b.py

from MyImportError import MyImportError

try:
    import nonexistantmoduletocauserror
except ImportError:
    raise MyImportError("Error: It seems nonexistantmoduletocauserror.py does not exist!")

修改

好的,我明白了,然后再尝试一下:

档案a.py

import traceback
import sys
import importlib

try:
    importlib.import_module("b")
except ImportError as e:
    exc_type, exc_obj, tb = sys.exc_info()
    print(exc_type)
    print(exc_obj)
    traceback.print_exc()

档案b.py

import nonexistantmoduletocauserror

您将看到包含相关错误消息的完整回溯:

Traceback (most recent call last):
  File "/Users/darius/code/python/sklearn-keras/examples/a.py", line 8, in <module>
    importlib.import_module("b")
  File "/Users/darius/anaconda2/envs/sklearn-keras/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/darius/code/python/sklearn-keras/examples/b.py", line 3, in <module>
    import nonexistantmoduletocauserror
ImportError: No module named nonexistantmoduletocauserror

<type 'exceptions.ImportError'>
No module named nonexistantmoduletocauserror

答案 1 :(得分:1)

load_module()现已弃用。他们说使用exec_module()代替。事实上,这提供了一个解决方案,因为导入现在分两个阶段进行:找到模块,然后执行它。请参阅文档中的“检查是否可以导入模块”,此处为:https://docs.python.org/3/library/importlib.html#checking-if-a-module-can-be-imported

在您的情况下,代码看起来像:

spec = importlib.util.find_spec('b')
if spec is None:
    print("it seems b.py does not exist!")
else:
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)