【问题标题】:Python: getting segmentation fault when using compile/evalPython:使用编译/评估时出现分段错误
【发布时间】:2011-10-10 08:46:09
【问题描述】:

代码:

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,我遇到了分段错误。为什么?


【问题讨论】:

    标签: python compilation segmentation-fault cpython pypy


    【解决方案1】:

    我猜你的函数定义不能有一个空的主体。我通过添加一个 no-op 语句作为函数体来测试您的代码:

    fAst = ast.FunctionDef(
        # ...
        body=[ast.Pass()],
        # ...
    

    分段错误消失了;输出是:

    如果我是正确的,这可能是 ast 模块中的错误,因为它应该检查空正文。

    【讨论】:

    • 如果你定义了一个空函数,而没有在函数主体中添加pass,那么Python会给你一个语法错误,不是吗?
    • 确实如此。但它不会出现段错误。
    • 这是因为当前 AST 没有经过验证,当您尝试编译 AST 以避免此类问题时,CPython 中有一个开放票可以向 AST 添加验证器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 2020-07-04
    • 2021-10-23
    • 1970-01-01
    • 2023-03-16
    • 2011-09-27
    相关资源
    最近更新 更多