如何非递归地捕获 ImportError? (动态导入)

How to catch an ImportError non-recursively? (dynamic import)

假设我们要动态导入脚本,即名称是在运行时构造的。我用它来检测某些程序的插件脚本,因此脚本可能不存在并且导入可能会失败。

from importlib import import_module
# ...
subpackage_name = 'some' + dynamic() + 'string'
try:
    subpackage = import_module(subpackage_name)
except ImportError:
    print('No script found')

我们如何确保只捕获插件脚本本身可能的导入失败,而不捕获插件脚本内部可能包含的导入?

旁注:this question 是相关的,但它是关于静态导入的(使用 import 关键字),提供的解决方案在这里不起作用。

自 Python 3.3 起,ImportError 对象具有 namepath 属性,因此您可以捕获错误并检查导入失败的名称。

try:
    import_module(subpackage_name)
except ImportError as e:
    if e.name == subpackage_name:
        print('subpackage not found')
    else:
        print('subpackage contains import errors')
Python 中的

ImportError 可以阅读的消息 name 如果有异常对象可以使用的属性:

# try to import the module
try:
    subpackage = import_module(subpackage_name)

# get the ImportError object
except ImportError as e:

    ## get the message
    ##message=e.message

    ## ImportError messages start with "No module named ", which is sixteen chars long.
    ##modulename=message[16:]

    # As Ben Darnell pointed out, that isn't the best way to do it in Python 3
    # get the name attribute:
    modulename=e.name

    # now check if that's the module you just tried to import
    if modulename==subpackage_name:
        pass

        # handle the plugin not existing here

    else:
        # handle the plugin existing but raising an ImportError itself here

# check for other exceptions
except Exception as e:
    pass
    # handle the plugin raising other exceptions here