gpt4 book ai didi

python - 运行动态编译的代码对象时,如何在回溯中保留源代码行?

转载 作者:行者123 更新时间:2023-11-30 22:49:45 33 4
gpt4 key购买 nike

假设我使用compile从字符串和名称创建 code 对象:

>>> a = compile('raise ValueError\n', '<at runtime>', 'exec')

我希望该字符串中的行出现在回溯中(注意 - 以下是在 IDLE 中运行):

>>> exec(a)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
exec(c)
File "<at runtime>", line 1, in <module>
raise ValueError <-- This line is what I want
ValueError

唉,他们没有:

>>> exec(a)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
exec(c)
File "<at runtime>", line 1, in <module>
ValueError

在不创建临时文件的情况下,如何使 raise ValueError 行出现在回溯中?

最佳答案

使用内置 linecache 中未记录的 cache 成员,这似乎有效:

def better_compile(src, name, mode):
# there is an example of this being set at
# https://hg.python.org/cpython/file/2.7/Lib/linecache.py#l104
from linecache import cache
cache[name] = (
len(src), None,
[line+'\n' for line in src.splitlines()], name
)
return compile(src, name, mode)
>>> c = better_compile('raise ValueError\n', '<a name>', 'exec')
>>> exec(c)
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
exec(c)
File "<a name>", line 1, in <module>
raise ValueError
ValueError
<小时/>

原来这是pretty much how IDLE does it

关于python - 运行动态编译的代码对象时,如何在回溯中保留源代码行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39625465/

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