How to do a program dump - reposted

Richie Hindle richie at
Mon Aug 19 14:59:49 CEST 2002

> Is there a way how to do a dump ( e.g. print line and the last successully executed command 
> from my Python program ) when there is a General Protection Error ?

When I have to contend with a crash like this, I use a "black box
recorder" module which logs every line executed to a file.  You get
big output and tremendously slow execution, but it does tell you
where the crash happened and how the program got there.  Use it like

>>> import blackbox, calendar
>>> blackbox.recordTo( open( 'log.txt', 'wt' ) )
>>> calendar.weekday( 2002, 8, 19 )
>>> ^Z

> type log.txt

To use it in a program, call `recordTo` conditionally on a command-line
switch or something.

---------------------------- --------------------------

import sys

outputStream = None

def recordTo( stream ):
   global outputStream
   outputStream = stream
   sys.settrace( globalTrace )

def globalTrace( frame, event, arg ):
   if event == 'line':
      outputStream.write( "%s:%d\n" % ( frame.f_code.co_filename, frame.f_lineno ) )
   elif event == 'exception':
      (exception, value, traceback) = arg
      outputStream.write( "%s:%d Exception: %s\n" % ( frame.f_code.co_filename, frame.f_lineno, exception ) )
   return globalTrace

-------------------------------- end ------------------------------

With a bit of extra work, you could get it to indent the log file to
reflect the call stack.

Hope that helps.


More information about the Python-list mailing list