This should work:
import inspect
try:
some_bad_code()
except Exception, e:
frm = inspect.trace()[-1]
mod = inspect.getmodule(frm[0])
print 'Thrown from', mod.__name__
EDIT: Stephan202 mentions a corner case. In this case, I think we could default to the file name.
import inspect
try:
import bad_module
except Exception, e:
frm = inspect.trace()[-1]
mod = inspect.getmodule(frm[0])
modname = mod.__name__ if mod else frm[1]
print 'Thrown from', modname
The problem is that if the module doesn't get loaded (because an exception was thrown while reading the code in that file), then the inspect.getmodule
call returns None. So, we just use the name of the file referenced by the offending frame. (Thanks for pointing this out, Stephan202!)