How to get actual line number of where python exception occurred?
<p>I have the following python decorator in my file <code>decorators.py</code></p>

<pre><code>def catch_exceptions(function):                                           #Line #1
    @wraps(function)                                                      #Line #2
    def decorator(*args, **kwargs):                                       #Line #3
        try:                                                              #Line #4
            return function(*args, **kwargs)                              #Line #5
        except Exception as e:                                            #Line #6
            exc_type, exc_obj, exc_tb = sys.exc_info()                    #Line #7
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]  #Line #8
            print "E=%s, F=%s, L=%s" % (str(e), fname, exc_tb.tb_lineno)  #Line #9
    return decorator                                                      #Line #10
</code></pre>

<p>In another file <code>my_file.py</code>, I use the <code>catch_exceptions</code> decorator like this:</p>

<pre><code>from decorators import catch_exceptions                                   #Line #1
@catch_exceptions                                                         #Line #2
def my_method()                                                           #Line #3
    print (10/0 - 5/0)                                                    #Line #4
</code></pre>

<p>When I run it, I get the following output:</p>

<pre><code>E=integer division or modulo by zero, F=decorators.py, L=5
</code></pre>

<p>Instead of it reporting the exception location as <code>decorators.py</code>, line #5, How can I get it to report the actual file and line number of where the exception originally occurred? That would be line #4 in <code>my_file.py</code>.</p>

<p>You may want to look into the <code>traceback</code> module</p>

<pre><code>import traceback

try:
    function_that_raises_exception()
except Exception:
    traceback.print_exc()
</code></pre>

<p>It will print the entire stack trace.</p>

python django exception-handling