Python Tutorial

Friday, August 31, 2012

python dynamic code execution, exec exaqmple



Dynamic code execution is very important in some cases. Sometimes we need to generate code dynamically and then run it. Lets see a very simple example using exec:


 
v=5

code = """def myFun():
            global v
            v=10
            print 'This is my function'
       """
exec code

print v
myFun() #must execute the code before calling function
print v



Output:
5
This is my function
10

0 comments:

Post a Comment