Executing Code Inside Strings


codeStr = "for card in cards: \     print \"Card = \" + card" exec(codeStr)

One of the most dynamic features of Python is the capability to evaluate a string that contains code and execute the code locally. The exec(str [,globals [,locals]]) function will execute Python code that is contained in the str string and return the result. Local and global variables can be added to the environment used to execute the code by specifying global and/or local dictionaries containing corresponding variable name and values.

The eval(str [,globals [,locals]]) function works in a similar manner as the exec function except that it only evaluates the string as a Python expression and returns the results.

cards = ['Ace', 'King', 'Queen', 'Jack'] codeStr = "for card in cards: \     print \"Card = \" + card" areaStr = "pi*(radius*radius)" #Execute string exec(codeStr) #Evaluate string print "\nArea = " + str(eval(areaStr, \     {"pi":3.14}, {"radius":5}))


eval_str.py

Card = Ace Card = King Card = Queen Card = Jack Area = 78.5


Output from eval_str.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net