Capturing exceptions?

Larry Bates lbates at swamisoft.com
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')
    f.writelines(tblines)
    f.close()
    sys.exit(0)

Then in main program

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




"Dfenestr8" <chrisdewinN0SPAM at yahoo.com.au> wrote in message
news:pan.2004.08.25.17.12.17.521438 at yahoo.com.au...
> 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