gpt4 book ai didi

python - 你如何编译 ast.Expr?

转载 作者:太空宇宙 更新时间:2023-11-04 02:15:14 25 4
gpt4 key购买 nike

code='1+1'
import ast
expr = ast.parse(code).body[0]
print(type(expr))
compile(ast.Expression(expr), 'string', "eval")

让我明白

class '_ast.Expr'

Traceback (most recent call last): File "test_ast.py", line 6, in compile(ast.Expression(expr), '', "eval") TypeError: expected some sort of expr, but got <_ast.Expr object at> 0x7fe89442d9e8>

compile(expr, '<string>', "eval")

也不行:

TypeError: expected Expression node, got Expr

最佳答案

TLDR:用 ast.Expression(expr.value) 替换 expr

对此Convert ast node into python object的评论makeMonday answer 给了我解决方案:

code = 'a+1'
import ast
expr = ast.parse(code).body[0]
print(eval(compile(ast.Expression(expr.value), '<string>', "eval"), {"a": 4}, {}))

关于python - 你如何编译 ast.Expr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52819981/

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