简体   繁体   中英

How can i get out the error line text in python exceptions?

Can i get the line text from <string > filename?

Example code :

exec("""
print()
0 / 0
""")

Output :

Traceback (most recent call last):
  File "/data/data/com.termux/files/home/p.py", line 1, in <module>
    exec("""
  File "<string>", line 3, in <module>
ZeroDivisionError: division by zero

I need to get the line :

0 / 0

I will write it like this

try:
    exec("") 
except Exception as e:
    # Somthing like this
    print(e.linetext)

I know that i can write the exec codes in a string and read the lineno from error and check the line from exec codes string but in my project i have to launch a large codes with exec, that mean This will cause the files to increase in size, i need another way throw the Exception Please and thx ✨♥️

Use the traceback module

here is another way to achieve the same result

import sys, os

try:
    raise NotImplementedError("No error")
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    print(exc_tb.tb_lineno)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM