gpt4 book ai didi

python - linecache.getline() 什么都不返回

转载 作者:太空宇宙 更新时间:2023-11-04 10:32:03 24 4
gpt4 key购买 nike

我有一个函数可以放入 tryexcept 部分,我希望它记录错误信息。问题是我无法像以前那样获取产生错误的代码行。看看这段代码:

def func():
try:
a = 1
b = 0
print a / b
except:
Debug.log()

这是日志函数:

def log(cls):
try:
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
line_no = str(tb.tb_lineno)
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, line_no, f.f_globals)
current_frame = inspect.currentframe()
previous_frame = current_frame.f_back
func_name = previous_frame.f_code.co_name
msg = str(exc_obj)

obj = Error()
obj.filename = filename
obj.line_no = line_no
obj.line = line
obj.msg = msg
obj.function = func_name
obj.save()

执行后我可以看到该行是空的:

{
"_id" : ObjectId("5413d67a65765f16219aa575"),
"filename" : "E:/Developer Center/DomainServices/DomainServices/test.py",
"line_no" : "23",
"line" : "",
"msg" : "integer division or modulo by zero",
"function" : "func",
}

怎么了?

最佳答案

代码将 str 对象传递给 linecache.getline

line_no = str(tb.tb_lineno)
^^^

根据 linecache.py source code ,传递的行号与 1 和总行数进行比较:

    if 1 <= lineno <= len(lines):
return lines[lineno-1]
else:
return ''

因为 linenostr 对象,谓词在 Python 2.x 中被评估为 False(在 Python 3 中引发异常。 x 因为不允许比较 strint)

>>> 1 < '2' < 3
False

你得到一个空字符串。


您应该传递一个 int 对象。

line = linecache.getline(filename, int(line_no))

line = linecache.getline(filename, tb.tb_lineno)

关于python - linecache.getline() 什么都不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25820217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com