【问题标题】:How to catch an ImportError non-recursively? (dynamic import)如何以非递归方式捕获 ImportError? (动态导入)
【发布时间】:2015-03-01 19:43:55
【问题描述】:

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

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.x import importerror python-import


【解决方案1】:

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

【讨论】:

  • 我不知道这种改进。非常感谢!
【解决方案2】:

Python 中的ImportErrors 具有您可以阅读的消息 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

【讨论】:

  • 是的,新的名称属性效果更好,但无论如何你都会得到我的支持。
  • @Chiel92 是的,我通常使用 Python 2。
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2012-05-31
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多