简体   繁体   中英

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()

So if I have already given x & y values beforhand, I know that can write:

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.

How do I do this?

Have you checked the documentation for 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 :

in Python 2.x:

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

in 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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