[PyKDE] How to capture python tracebacks?

Dave Smith Dave.Smith at transcendata.com
Wed Sep 5 23:33:02 BST 2001


Hello all,

I'm trying to figure out a way to capture python traceback
messages that are apparently caught in the pyqt event loop
and issued to stdout.

For example, in the attached sample program, I would like
the tracebacks that occur when the 'Error' button is clicked
to be displayed in the multi line edit as well as stdout.

I thought about implementing the event loop in my PyQApplication
sub-class but could not find enough info to do it.  Has anyone
else done this?

Any other ideas?

Best regards,
Dave

-------------- next part --------------
#!/usr/bin/env python

import os
import sys
import string
import traceback
from qt import *

class PyQApplication (QApplication):
   def __init__ (self, argv):
      QApplication.__init__ (self, argv)

   def exec_loop (self):
      global multiLineEdit
      multiLineEdit.insertLine ("In PyQApplication.exec_loop()...")
      QApplication.exec_loop (self)

class PyQMainWindow (QMainWindow):

   def __init__ (self, parent = None, name = None, fl = 0):
      QMainWindow.__init__ (self, parent, name, fl)
      self.setCaption (self.tr ('Traceback Test'))
      buttonGroup = QButtonGroup (self.tr ('Traceback Test'), self, 'group')
      vBoxLayout = QVBoxLayout (buttonGroup)
      global multiLineEdit
      multiLineEdit = QMultiLineEdit (buttonGroup, 'edit')
      vBoxLayout.addWidget (multiLineEdit)
      badButton = QPushButton (self.tr ('&Error'), buttonGroup, 'bad')
      vBoxLayout.addWidget (badButton)
      self.connect (badButton, SIGNAL ('clicked()'), badFunc)
      quitButton = QPushButton (self.tr ('&Quit'), buttonGroup, 'quit')
      vBoxLayout.addWidget (quitButton)
      self.connect (quitButton, SIGNAL ('clicked()'), self, SLOT ('close()'))
      self.setCentralWidget (buttonGroup)

def getTraceback():
   lines = traceback.format_exception (sys.exc_type, sys.exc_value,
      sys.exc_traceback)
   return string.join (lines, '')

def badFunc():
   RaiseNameError 

def main():

   try:
      badFunc()
   except:
      print '-'*77
      print getTraceback()
      print '-'*77

   appTopLevel = PyQApplication (sys.argv)
   appMainWin = PyQMainWindow (None, 'main', Qt.WDestructiveClose)
   appMainWin.show()
   appTopLevel.connect (appTopLevel, SIGNAL ('lastWindowClosed()'),
      appTopLevel, SLOT ('quit()'))
   appTopLevel.exec_loop()

if __name__ == "__main__" : main()



More information about the PyQt mailing list