如何在'eval'模式下编译ast节点
How to compile ast node in 'eval' mode
我想创建一个代码对象,以后可以在 eval
中重复使用。我需要根据我以编程方式生成的一些 ast
节点来执行此操作,因此我无法将代码作为字符串传递给 compile
函数。如何构造一个有效的ast
节点进行编译?以下是我尝试过的几件事:
tree = ast.parse("2+2")
exe = compile(tree.body[0], filename="", mode="eval")
TypeError: expected Expression node, got Expr
tree = ast.BinOp(left=ast.Num(n=2), right=ast.Num(n=2), op=ast.Add())
exe = compile(tree, filename="", mode="eval")
TypeError: expected Expression node, got BinOp
tree = ast.BinOp(left=ast.Num(n=2), right=ast.Num(n=2), op=ast.Add())
expr = ast.Expression(body=[tree])
ast.fix_missing_locations(expr)
exe = compile(expr, filename="", mode="eval")
TypeError: required field "lineno" missing from expr
您的最后一次尝试很接近,但是 ast.Expression
的 body
应该是单个表达式,而不是表达式列表。
变化:
expr = ast.Expression(body=[tree])
至:
expr = ast.Expression(body=tree)
所以 eval(exe)
returns: 4
我想创建一个代码对象,以后可以在 eval
中重复使用。我需要根据我以编程方式生成的一些 ast
节点来执行此操作,因此我无法将代码作为字符串传递给 compile
函数。如何构造一个有效的ast
节点进行编译?以下是我尝试过的几件事:
tree = ast.parse("2+2")
exe = compile(tree.body[0], filename="", mode="eval")
TypeError: expected Expression node, got Expr
tree = ast.BinOp(left=ast.Num(n=2), right=ast.Num(n=2), op=ast.Add())
exe = compile(tree, filename="", mode="eval")
TypeError: expected Expression node, got BinOp
tree = ast.BinOp(left=ast.Num(n=2), right=ast.Num(n=2), op=ast.Add())
expr = ast.Expression(body=[tree])
ast.fix_missing_locations(expr)
exe = compile(expr, filename="", mode="eval")
TypeError: required field "lineno" missing from expr
您的最后一次尝试很接近,但是 ast.Expression
的 body
应该是单个表达式,而不是表达式列表。
变化:
expr = ast.Expression(body=[tree])
至:
expr = ast.Expression(body=tree)
所以 eval(exe)
returns: 4