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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With