Python catches any exception and traces a print or variable log

When I detect an unexpected error with sys.excepthook

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 

This is the result that I get

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

How to include variable values ​​(h, k, ...) in traceback simillar at http://www.doughellmann.com/PyMOTW/cgitb/ ? When I include the cgitb result, it is the same.

EDIT:

Great answer. I just changed it so that it would record the trace in the file.

 def handleException(excType, excValue, trace): cgitb.Hook(logdir=os.path.dirname(__file__), display=False, format='text')(excType, excValue, trace) 
+6
source share
1 answer

cgitb.py looking at the source of cgitb.py , you can use something like this:

 import sys import traceback import cgitb def handleException(excType, excValue, trace): print 'error' cgitb.Hook(format="text")(excType, excValue, trace) sys.excepthook = handleException h = 1 k = 0 print h/k 
+8
source

Source: https://habr.com/ru/post/904914/


All Articles