0

Hi,
If I execute the following code I will get the the output as 2. What I need is to execute the string str. Is there a way that I can execute the string str , as it is so I will get the output as 5.

def add(a,b):
    return a+b

var = 2
str = "var = add(2,3)"
# execute the code snippet inside the str string variable
print var
4
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by Ene Uran
0
>>> exec("print 2")
2
>>> exec("print 2+2")
4
>>> exec("vars = (var1, var2, var3, var4) = 'a', (1,'2',3.0), 44, 0.7\nfor v in vars:\n    print v, '=', type(v)")
a = <type 'str'>
(1, '2', 3.0) = <type 'tuple'>
44 = <type 'int'>
0.7 = <type 'float'>
0

You need exec compile(str, '<string>', 'exec') Alternatively, if str is just an expression (like add(2,3) ) you can do an eval(str) and get back 5. So exec for statements, eval for expressions.

0

In a nutshell:

def add(a, b):
    return a + b

var = 2
str = "var = add(2, 3)"
# execute the code snippet inside the str string variable
exec(str)
print var  # --> 5
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.