您如何编译ast.Expt? [英] How do you compile an ast.Expt?
问题描述
code='1+1'
import ast
expr = ast.parse(code).body[0]
print(type(expr))
compile(ast.Expression(expr), 'string', "eval")
让我
class'_ast.Expr'
class '_ast.Expr'
Traceback(最近一次调用的最后一次):文件
test_ast.py,第6行,在
中compile(ast.Expression(expr),'', eval)TypeError:期望某种形式的expr,但是在< _ast.Expr对象位于> 0x7fe89442d9e8>
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:预期的表达式节点,得到了Expr
TypeError: expected Expression node, got Expr
推荐答案
TLDR:用ast.Expression(expr.value)替换expr
TLDR : replace expr by ast.Expression(expr.value)
对此将ast节点转换为python对象和m akeMonday答案给了我解决方案:
A comment on this Convert ast node into python object and makeMonday answer gave me the solution:
code = 'a+1'
import ast
expr = ast.parse(code).body[0]
print(eval(compile(ast.Expression(expr.value), '<string>', "eval"), {"a": 4}, {}))
这篇关于您如何编译ast.Expt?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!