How to do a program dump - reposted

Richie Hindle richie at entrian.com
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
this:

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

> type log.txt
<stdin>:0
<stdin>:1
d:\python\lib\calendar.py:46
d:\python\lib\calendar.py:47
d:\python\lib\calendar.py:48
d:\python\lib\calendar.py:49

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

---------------------------- blackbox.py --------------------------

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 ) )
      outputStream.flush()
   elif event == 'exception':
      (exception, value, traceback) = arg
      outputStream.write( "%s:%d Exception: %s\n" % ( frame.f_code.co_filename, frame.f_lineno, exception ) )
      outputStream.flush()
   
   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.

-- 
Richie




More information about the Python-list mailing list