Use exec function to execute a string in Python

Use exec function to execute a string

The following code execute "print 'Hello, world!'" and prints out the message of "Hello, world!".

exec function executes a string.


exec "print 'Hello, world!'" 

The code above generates the following result.


cards = ['A', 'K', 'Q', 'J']
codeStr = "for card in cards: print \"Card = \" + card"

exec(codeStr)

The code above generates the following result.

We can also use exec to execute a compiled code returned from compile function.


single_code = compile('print "Hello world!"', '', 'single')
exec single_code

The code above generates the following result.

Execute several statements.


exec """
x = 0# from  w ww.j  av a 2  s  . c  o  m
print  'x is currently:', x
while  x < 5:
    x += 1
    print 'incrementing x to:', x
"""

The code above generates the following result.

exec can accept a valid file object to a (valid) Python file.


f = open('test.py')        # open the file
exec f                     # execute the file




















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules