In Python, import does_not_exist
raises ImportError
, and
import exists
exists.py
:
import does_not_exist
will also raise ImportError
.
How should I tell the difference in code?
In Python, import does_not_exist
raises ImportError
, and
import exists
exists.py
:
import does_not_exist
will also raise ImportError
.
How should I tell the difference in code?
The only method I know is to check if the toplevel modulename "exists" is in the Exception's message or not:
try:
import exists
except ImportError as exc:
if "exists" in str(exc):
pass
else:
raise
Could this be a feature request for Python's ImportError? Having a variable for the module name would certainly be convenient..
You can use the tb_next of the traceback. It will be different from None if the exception occured on another module
import sys
try:
import exists
except Exception, e:
print "None on exists", sys.exc_info()[2].tb_next == None
try:
import notexists
except Exception, e:
print "None on notexists", sys.exc_info()[2].tb_next == None
>>> None on exists False
>>> None on notexists True