Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top