简体   繁体   English

使用地图中的eval()执行python代码行

[英]Executing a python line of code using eval() from a map

Let's say that I have a line of code that is a string: 假设我有一行代码是字符串:

a="print 'x + y = ', x + y"

Now I want to execute it using eval() 现在我想用eval()执行它

So if I have already given x & y values beforhand, I know that can write: 所以如果我已经给出了x&y值,我知道可以写:

eval (compile (a,"test.py", "single"))

And it will work great. 它会很棒。

But I want to give them values from a dict. 但我想给他们一个字典的价值。 In other words, if I have a dict: 换句话说,如果我有一个词典:

b={'x':4,'y':3}

I want the values that will go into x & y to come from b. 我想要进入x和y的值来自b。

How do I do this? 我该怎么做呢?

Have you checked the documentation for eval() ? 你检查了eval()文档吗? There's a couple more parameters you can use for exactly this purpose. 您可以使用更多参数来实现此目的。 For example: 例如:

>>> b = {'x':4,'y':3}
>>> eval("x + y", b)
7

For statements, you should use exec : 对于语句,您应该使用exec

in Python 2.x: 在Python 2.x中:

exec "print 'x + y = ', x + y" in {'x':4,'y':3}

in Python 3.x: 在Python 3.x中:

exec("print('x + y = ', x + y)", {'x':4,'y':3})

(of course, print is not a statement in Python 3, so there is no need in this case) (当然, print不是Python 3中的声明,因此在这种情况下不需要)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM