gpt4 book ai didi

python - Python 从哪里获取 traceback entry 字段

转载 作者:行者123 更新时间:2023-11-28 17:38:47 24 4
gpt4 key购买 nike

每个回溯项的格式如下:

File "<filename>", line xxx, in <module>
line

我有兴趣更改某些模块的文件名字段(自定义)。这可能吗?我试过修改模块对象的 __file__ 成员,但是当 python 生成回溯堆栈时似乎没有使用它。

最佳答案

您可以使用inspect 模块来获取许多模块的文件路径。例如

>>> inspect.getabsfile(traceback)
'/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/traceback.py'

知道回溯来自traceback.print_stack() ,然后我们可以查看 print_stack() 的定义:

279 def print_stack(f=None, limit=None, file=None):
280 """Print a stack trace from its invocation point.
281
282 The optional 'f' argument can be used to specify an alternate
283 stack frame at which to start. The optional 'limit' and 'file'
284 arguments have the same meaning as for print_exception().
285 """
286 print_list(extract_stack(_get_stack(f), limit=limit), file=file)

用“它在哪里定义?”顺便说一下,我会为您省去跟踪函数调用的麻烦,并建议查看 format_exceptionrelevant examples .在不知 Prop 体要对回溯做什么的情况下,我建议查看 jinja2 source因为它做了相当多的回溯处理。

关于python - Python 从哪里获取 <filename> traceback entry 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27487106/

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