Capturing exceptions?

Larry Bates lbates at
Wed Aug 25 19:29:28 CEST 2004

You need to set up an exception hook function, register
it with Python and have it write out the traceback
information to your file.

def excepthook(type, value, tb):
    # This function allows the user to redefine what happens if the program
    # aborts due to an uncaught exception.
    import traceback
    # Get traceback lines and append the current session log
    tblines=traceback.format_exception(type, value, tb)
    # Insert code to write to file here
    f=open('traceback.log', 'a')

Then in main program

    # Set the sys.excepthook so I can clean up properly if main program

"Dfenestr8" <chrisdewinN0SPAM at> wrote in message
news:pan.2004. at
> Hi.
> What's the easiest way to capture the traceback from an exception, and
> write it to a file? Ideally, I'd like to be able to do something like:
> >try:
> > main()
> >except:
> > write the traceback to a file

More information about the Python-list mailing list