英文:
Getting formatted traceback when overwriting sys.excepthook
问题
我正在重述这个问题,因为我在初始问题中遇到了一些问题,而且太模糊了。
我正在尝试构建一个替代sys.excepthook函数的函数,以便在运行批处理作业时将错误保存到文件。我已经参考了几个来源,但特别是在将回溯打印到文件时遇到了问题。以下是对我有效的一些内容。
import sys
import traceback
def saveError(exctype, value, tb):
filename = tb.tb_frame.f_code.co_filename
name = tb.tb_frame.f_code.co_name
line_no = tb.tb_lineno
with open('filepath.txt', 'w', newline='') as f:
f.write(f"{filename}")
f.write(f"{name}")
f.write(f"{line_no}")
f.write(f"{exctype.__name__}")
f.write(f"{value}")
f.close()
sys.excepthook = saveError
print(1/0)
我遇到的问题是尝试打印完整的回溯,你可以在上面看到我已经提取了它的各个部分,但无法获取整个回溯。下面是我尝试过的一些示例。
import traceback
trace = f"{traceback.format_exc()}"
这返回NoneType: None
f.write(f"{tb}")
这返回<traceback object at 0x7....
trace2 = traceback.format_tb(tb)
这似乎什么都没有返回
有没有办法将回溯信息以字符串格式获取并保存到文件中?
英文:
I am rewording this question, as it seems I had some issues in my initial question and it was too vague.
I am working on trying to build a replacement function for sys.excepthook to save errors to file when running a batch job. I have referenced several sources and and am specifically having trouble getting the traceback to print to file. Below is something that is working for me.
import sys
import traceback
def saveError(exctype, value, tb):
filename = tb.tb_frame.f_code.co_filename
name = tb.tb_frame.f_code.co_name
line_no = tb.tb_linno
with open('filepath.txt','w', newline = '') as f:
f.write(f"{filename}")
f.write(f"{name}")
f.write(f"{line_no}")
f.write(f"{exctype.__name__}")
f.write(f"{value}")
f.close()
sys.excepthook = saveError
print(1/0)
The problem I'm running into is trying to print the full traceback, you can see above I've pulled out individual pieces of it but haven't been able to get the whole thing. A few examples of things I've tried below.
import traceback
trace = f"{traceback.format_exc()}"
This returns NoneType: None
f.write(f"{tb}")
This returns <traceback object at 0x7....
trace2 = traceback.format_tb(tb)
This seems to return nothing
Is there a way to get the traceback information into a string format and save it to file?
答案1
得分: 1
一个回溯对象没有这些方法。您需要 import traceback
然后使用 traceback.print_exc(...)
等。
英文:
A traceback object doesn't have those methods. You need to import traceback
and then traceback.print_exc(...)
etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论