区分由于找不到模块而导致的 ImportError 或 python 中模块本身的错误导入?

2024-04-23

我在 python 中有一些模块,它们是动态导入的,并且都具有相同的结构(plugin.py、models.py、tests.py,...)。在管理代码中,我想导入这些子模块,但例如 models.py 或tests.py 不是强制性的。 (所以我可以有plugin_a.plugin and plugin_a.tests但只有plugin_b.plugin).

我可以检查子模块是否存在

try:
    __import__(module_name + ".tests")
except ImportError:
    pass

那将会失败,如果module_name+".tests"找不到,但如果tests-module 本身会尝试导入一些未找到的内容,例如由于拼写错误。 有没有办法检查模块是否存在,而不导入它或确保模块ImportError仅由一项特定进口行动引发?


你可以从回溯的长度导入失败的深度有多少。一个失踪的.test模块只有一帧的回溯,直接依赖失败有两帧,等等。

Python 2版本,使用sys.exc_info() https://docs.python.org/2/library/sys.html#sys.exc_info访问回溯:

import sys


try:
    __import__(module_name + ".tests")
except ImportError:
    if sys.exc_info()[-1].tb_next is not None:
        print "Dependency import failed"
    else:
        print "No module {}.tests".format(module_name)

Python 3 版本,其中例外有一个__traceback__属性 https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement:

try:
    __import__(module_name + ".tests")
except ImportError as exc:
    if exc.__traceback__.tb_next is not None:
        print("Dependency import failed")
    else:
        print("No module {}.tests".format(module_name))

Demo:

>>> import sys
>>> def direct_import_failure(name):
...     try:
...         __import__(name)
...     except ImportError:
...         return sys.exc_info()[-1].tb_next is None
... 
>>> with open('foo.py', 'w') as foo:
...     foo.write("""\
... import bar
... """)
... 
>>> direct_import_failure('bar')
True
>>> direct_import_failure('foo')
False
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

区分由于找不到模块而导致的 ImportError 或 python 中模块本身的错误导入? 的相关文章

随机推荐