[英]Python stacktrace module traceback line error
I have the following Python program: 我有以下Python程序:
import traceback
import sys
try:
3/0
except OverflowError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
formatted_lines = traceback.format_exc().splitlines()
print(" It looks like in the arithmetic operation :" , formatted_lines[2], " ) #gets the offending line
print (at line number " , exc_traceback.tb_lineno ) #gets the line number
except ZeroDivisionError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
formatted_lines = traceback.format_exc().splitlines()
print(" It looks like in the arithmetic operation :" , formatted_lines[2], " ) #gets the offending line
print (at line number " , exc_traceback.tb_lineno ) #gets t
For simple programs as above the stacktrace returns the correct line number, but for more complicated methods like below Python throws more stacktraces (the latest call being the last), is there a way to figure out the index of the stacktrace ex: formatted_lines[2]
to get the latest call. 对于像上面这样的简单程序,stacktrace返回正确的行号,但是对于像下面这样的更复杂的方法,Python会抛出更多的stacktrace(最后一次调用是最后一个),有没有办法找出stacktrace的索引,例如: formatted_lines[2]
获取最新通话。
try:
def prize():
print("hello")
def main():
prize()
Catch:
.....
any help would be appreciated. 任何帮助,将不胜感激。
Also tried this: 还尝试了这个:
import traceback
import sys
import linecache
try:
2/0
except ZeroDivisionError as e:
filename = exc_traceback.tb_frame.f_code.co_filename
lineno = exc_traceback.tb_lineno
line = linecache.getline(filename, lineno)
print "exception occurred at %s:%d: %s" % (filename, lineno, line)
I get an error on the last line "invalid syntax" 我在最后一行“无效语法”中收到错误
When I just try: 当我尝试时:
print (filename, lineno, line)
I get an error: 我收到一个错误:
Traceback (most recent call last):
File "C:\Users\Anu\Desktop\test.py", line 39, in <module>
filename = exc_traceback.tb_frame.f_code.co_filename
NameError: name 'exc_traceback' is not defined
Please don't try to parse stack traces using the output of format_exc
. 请不要尝试使用format_exc
的输出来解析堆栈跟踪。 That's only meant to produce a human-readable stack trace. 这仅是为了产生人类可读的堆栈跟踪。
You should instead use linecache
to get the offending line: 您应该改用linecache
来获取有问题的行:
exc_type, exc_value, exc_traceback = sys.exc_info()
filename = exc_traceback.tb_frame.f_code.co_filename
lineno = exc_traceback.tb_lineno
line = linecache.getline(filename, lineno)
print("exception occurred at %s:%d: %s" % (filename, lineno, line))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.