Capturing exceptions?

D

Dfenestr8

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:
 
M

Mathias Waack

Dfenestr8 said:
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:

Have a look at the traceback module.

Mathias
 
M

Michael Hudson

Dfenestr8 said:
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:

Read up on the traceback module.

Cheers,
mwh
 
L

Larry Bates

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
 
D

Dfenestr8

Have a look at the traceback module.

Mathias

I did. Thanx. But I'm afraid I don't understand it.

From looking at the docs, it would appear the method extract.tb(traceback,
limit) is the method I want. But it appears to want some kind of object as
its parameter, and I have no idea what kind of object that is.

I've tried "a = traceback.extract_tb(tb)",
"traceback.extract_tb(traceback)", "traceback.extract_tb(sys.exc_info())".

What kind of parameter does it need?
 
M

Mathias Waack

Dfenestr8 said:
I did. Thanx. But I'm afraid I don't understand it.

import traceback
try: raise Exception, "python is so cool;)"
except: traceback.print_exc(None,file("exc.trc","w"))

Does it that what you want?

Mathias
 
D

Dfenestr8

import traceback
try: raise Exception, "python is so cool;)" except:
traceback.print_exc(None,file("exc.trc","w"))

Does it that what you want?

Mathias

yep. Should do.

Thanx.

PS: Still would like to know what kind of parameter that other method
wants.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top