Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch an ImportError non-recursively?

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?

like image 504
chtenb Avatar asked Nov 02 '22 09:11

chtenb


1 Answers

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.

like image 180
Blender Avatar answered Nov 15 '22 05:11

Blender