Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find module name of the originating exception in Python

Example:

>>> try:
...    myapp.foo.doSomething()
... except Exception, e:
...    print 'Thrown from:', modname(e)

Thrown from: myapp.util.url

In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the __name__ of that module?

My intention is to use this in logging.getLogger function.

like image 854
Sridhar Ratnakumar Avatar asked Jul 08 '09 00:07

Sridhar Ratnakumar


People also ask

How do I identify exceptions in Python?

To get exception information from a bare exception handler, you use the exc_info() function from the sys module. The sys. exc_info() function returns a tuple that consists of three values: type is the type of the exception occurred.

What is exception module in Python?

The exceptions module provides the standard exception hierarchy. It's automatically imported when Python starts, and the exceptions are added to the _ _builtin_ _ module. In other words, you usually don't need to import this module. This is a Python module in 1.5. 2, and a built-in module in 2.0 and later.

What is module exception?

Module exemption means recognition that is granted within the framework of the admissions requirements of accredited learning from an approved or accredited provider, which is usually confirmed by means of academic records.


2 Answers

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

like image 99
ars Avatar answered Oct 05 '22 18:10

ars


You can use the traceback module, along with sys.exc_info(), to get the traceback programmatically:

try:
    myapp.foo.doSomething()
except Exception, e:
    exc_type, exc_value, exc_tb = sys.exc_info()
    filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
    print 'Thrown from: %s' % filename
like image 31
Adam Rosenfield Avatar answered Oct 05 '22 19:10

Adam Rosenfield