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

时间:2015-03-01 19:43:56

标签: python-3.x import importerror python-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关键字),并且提供的解决方案在此处不起作用。

2 个答案:

答案 0 :(得分:2)

自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')

答案 1 :(得分:1)

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