getting source code line of error?
Paolo G. Cantore
paolo.cantore at t-online.de
Sat Nov 20 18:20:02 EST 2021
Am 20.11.21 um 20:15 schrieb Ulli Horlacher:
> Stefan Ram <ram at zedat.fu-berlin.de> wrote:
>> ram at zedat.fu-berlin.de (Stefan Ram) writes:
>>> except Exception as inst:
>>> print( traceback.format_exc() )
>>
>> More to the point of getting the line number:
>
> As I wrote in my initial posting:
> I already have the line number. I am looking for the source code line!
>
> So far I use:
>
> m = re.search(r'\n\s*(.+)\n.*\n$',traceback.format_exc())
> if m: print('%s %s' % (prefix,m.group(1)))
>
Stefan Ram's solution missed only the line content. Here it is.
import sys
import traceback
try:
1/0
except ZeroDivisionError as exception:
tr = traceback.TracebackException.from_exception( exception )
x = tr.stack[0]
print("Exception %s in line %s: %s" % (exception, x.lineno, x.line))
The traceback object does not only contain the lineno but also the
content of the offending line.
--------------
Paolo
More information about the Python-list
mailing list