获取格式化的回溯信息,当覆盖 sys.excepthook 时

huangapple go评论50阅读模式
英文:

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(&#39;filepath.txt&#39;,&#39;w&#39;, newline = &#39;&#39;) as f:
        f.write(f&quot;{filename}&quot;)
        f.write(f&quot;{name}&quot;)
        f.write(f&quot;{line_no}&quot;)
        f.write(f&quot;{exctype.__name__}&quot;)
        f.write(f&quot;{value}&quot;)
    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&quot;{traceback.format_exc()}&quot;

This returns NoneType: None

f.write(f&quot;{tb}&quot;)

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.

huangapple
  • 本文由 发表于 2023年3月31日 22:53:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定