How to catch an ImportError non-recursively?

倖福魔咒の 提交于 2019-12-05 01:22:13

问题


Say we want to import a script named user.py, which may fail.

try:
   import user
except ImportError:
   logging.info('No user script loaded.')

How can we make sure to only catch the possible import failure of user.py itself, and not of the imports that may be contained in user.py?


回答1:


You could check to see if the current traceback is part of a chain of tracebacks:

import sys

try:
    import user
except ImportError:
    if sys.exc_info()[2].tb_next:
        raise

    logging.info('No user script loaded.')

If there is an ImportError in user, sys.exc_info()[2].tb_next will point to it.




回答2:


You could look at the arguments:

try:
   import user
except ImportError as exception:
    if 'user' == exception.args[0][16:]:
        logging.info('No user script loaded.')

This ensures you'll only log that message when the user script fails to be imported.

Although, it can be argued that failing to import one of the imports in user also implies that it can't import user (which means you'd need to log the message anyway).



来源:https://stackoverflow.com/questions/20459166/how-to-catch-an-importerror-non-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!