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
>>> 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'>

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.

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.