0
我見過Launch an IPython shell on exception,但這對我來說並沒有幫助(測試Python 2.7.1,Ubuntu 11.04)。請看下面的例子:從一個GUI事件(wx按鈕)上啓動一個PDB外殼異常
import wx
class Tester(object):
def __init__(self, innum):
print("innum: " +str(innum))
for x in xrange(innum,-1,-1):
tval = float(innum)/x
print(tval)
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Except Test")
self.btn = wx.Button(self, -1, "Click me")
self.btn.SetBackgroundColour(wx.NamedColour("orange"))
psizer = wx.BoxSizer(wx.HORIZONTAL)
psizer.Add(self.btn, 1, wx.EXPAND | wx.ALL, 20)
self.SetSizer(psizer)
self.SetSize((200,200))
self.btn.Bind(wx.EVT_BUTTON, self.runTest)
self.Layout()
def runTest(self, event):
t = Tester(3)
print(t)
if __name__ == '__main__':
runWx = True# False#
if not(runWx):
t = Tester(3)
print(t)
else:
app = wx.App(0)
frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()
如果我設置runWx
到False
,所以程序的命令行嚴格運行,一切都如預期:
$ python -m pdb test.py
> /tmp/test.py(1)<module>()
-> import wx
(Pdb) c
innum: 3
1.0
1.5
3.0
Traceback (most recent call last):
File "/usr/lib/python2.7/pdb.py", line 1314, in main
pdb._runscript(mainpyfile)
File "/usr/lib/python2.7/pdb.py", line 1233, in _runscript
self.run(statement)
File "/usr/lib/python2.7/bdb.py", line 387, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "test.py", line 1, in <module>
import wx
File "test.py", line 7, in __init__
tval = float(innum)/x
ZeroDivisionError: float division by zero
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /tmp/test.py(7)__init__()
-> tval = float(innum)/x
(Pdb) p x
0
(Pdb) q
Post mortem debugger finished. The test.py will be restarted
> /tmp/test.py(1)<module>()
-> import wx
(Pdb) q
...也就是說,當例外情況,pdb
提出驗屍殼,我可以檢查數值,並退出程序。
但是,如果runWx
是True
,就像在代碼中一樣,那麼我必須點擊GUI上的按鈕來引發一個異常;而在這種情況下,我得到這個:
$ python -m pdb test.py
> /tmp/test.py(1)<module>()
-> import wx
(Pdb) c
innum: 3
1.0
1.5
3.0
Traceback (most recent call last):
File "test.py", line 22, in runTest
t = Tester(3)
File "test.py", line 7, in __init__
tval = float(innum)/x
ZeroDivisionError: float division by zero
...那就是 - 沒有pdb
殼顯示,而不是輸出端打印回溯(事實上,你可以點擊後簡單地堵按鈕,並反覆在終端上打印回溯曲線,同時不會掉到pdb
殼)。
在wx
(或任何)GUI事件引發未處理的異常時,是否可以下載到pdb
shell?如果是,我如何在上面的示例中執行此操作?