Python catch any exception, and print or log traceback with variable values
<p>When I catch unexpected error with sys.excepthook </p>

<pre><code>import sys
import traceback

def handleException(excType, excValue, trace):
    print 'error'
    traceback.print_exception(excType, excValue, trace)

sys.excepthook = handleException

h = 1
k = 0

print h/k
</code></pre>

<p>This is output I get</p>

<pre><code>error
Traceback (most recent call last):
   File "test.py", line 13, in &lt;module&gt;
      print h/k
ZeroDivisionError: integer division or modulo by zero
</code></pre>

<p>How can I include variable values (h, k, ...) in traceback simillar to <a href="http://www.doughellmann.com/PyMOTW/cgitb/" rel="nofollow">http://www.doughellmann.com/PyMOTW/cgitb/</a> ? When I include cgitb result is same.</p>

<p><strong>EDIT:</strong></p>

<p>Great answer I only modified it like this so it logs trace in a file</p>

<pre><code>def handleException(excType, excValue, trace):
    cgitb.Hook(logdir=os.path.dirname(__file__),
      display=False,
      format='text')(excType, excValue, trace)
</code></pre>
