Python: 使用compile/eval时出现分段错误
代码:
import ast
globalsDict = {}
fAst = ast.FunctionDef(
name="foo",
args=ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]),
body=[], decorator_list=[])
exprAst = ast.Interactive(body=[fAst])
ast.fix_missing_locations(exprAst)
compiled = compile(exprAst, "<foo>", "single")
eval(compiled, globalsDict, globalsDict)
print globalsDict["foo"]
我在使用CPython和PyPy时都遇到了段错误。这是为什么呢?
1 个回答
5
我想你的函数定义里不能有空的内容。为了测试你的代码,我在函数里加了一条什么都不做的语句:
fAst = ast.FunctionDef(
# ...
body=[ast.Pass()],
# ...
这样一来,程序崩溃的问题就解决了,输出结果是:
<function foo at 0x022DB3F0>
如果我没猜错的话,这可能是ast
模块里的一个bug,因为它应该检查函数体是否为空。