从GUI事件(wx按钮)启动异常时启动PDB shell

时间:2015-01-15 18:09:26

标签: python wxpython pdb

我已经看过Launch an IPython shell on exception,但这对我没有帮助(在Python 2.7.1,Ubuntu 11.04上测试)。请考虑以下示例:

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会引发一个死后的shell,我可以检查值,然后退出程序。

但如果runWxTrue,就像在代码中一样,那么我必须单击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 shell,而输出终端在打印回溯后只是阻塞(实际上,您可以反复单击该按钮,并且反复在终端上打印回溯,而不会掉到pdb shell。

是否可以在pdb(或任何)GUI事件引发的未处理异常时删除wx shell - 如果是这样,我该如何在上面的示例中执行此操作?< / p>

1 个答案:

答案 0 :(得分:0)

我相信您所要做的就是导入pdb并在事件处理程序中设置跟踪:

def runTest(self, event):
    import pdb
    pdb.set_trace()
    t = Tester(3)
    print(t)

在Xubuntu 14.04上使用wxPython 2.8.12和Python 2.7对我有用。另见: