C macros in Python.
Quinn Dunkan
quinn at seniti.ugcs.caltech.edu
Sun Oct 15 00:36:18 EDT 2000
>"Steve Juranich" <sjuranic at condor.ee.washington.edu> wrote in message
>news:Pine.SOL.3.96.1001013105150.14155A-100000 at condor.ee.washington.edu...
>> I was just wondering if there was anything available in Python like the
>> __FILE__ and __LINE__ macros in C. I know about the __name__ attribute,
>but
>> I'm not sure that does exactly what I'm looking to do.
>>
>> What I'd like to do is write some code that will tell me _exactly_ on
>which
>> file and while line things went wrong.
On Fri, 13 Oct 2000 19:09:20 GMT, Olivier Dagenais
<olivierS.dagenaisP at canadaA.comM> wrote:
>You should be able to print out or inspect a traceback, if you catch an
>exception. Search on http://python.faqts.com for "CGI" (I think..) and one
>of the topics deals with printing out (to the browser) the traceback from a
>CGI script that failed. It's got an example on how to retrieve the
>traceback, which contains file names (if appropriate) and line numbers.
To be more explicit:
import sys
try:
my_func_which_may_fail()
except WhatItMightThrow, e:
t = sys.exc_info[2]
while t.tb_next:
t = t.tb_next
print 'got error', e, 'on line number', t.tb_lineno, 'in file', \
t.tb_frame.f_code.co_filename
That 'while' business walks back down the stack to get the bottom frame (the
one that actually threw the error). You probably would rather do:
import traceback
try:
my_func()
except:
traceback.print_exc()
which does all the tedious formatting for you. Of course, if you don't catch
the exception at all the same thing happens before the program quits :)
More information about the Python-list
mailing list