2012-01-02 94 views
6

登錄回溯當我趕上意外的錯誤與sys.excepthookPython中捕捉任何異常,並打印或與變量值

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 

這是輸出我得到

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

我怎麼能包括的變量值(h,k,...)在回溯類似於http://www.doughellmann.com/PyMOTW/cgitb/?當我包含cgitb的結果是一樣的。

編輯:

大答案,我只是修改了它這樣所以它記錄跟蹤文件中的

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

回答

8

通過查看cgitb.py源,你應該能夠使用像此:

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