Exec, Eval, and Execfile

The eval function

  • Evaluates a string as a Python expression
     a = eval("3*math.sin(3.5+x)+7.2")

The exec statement

  • Executes a string containing arbitrary Python code
     a = [3,5,10,13]
     exec "for i in a: print i"

The execfile function

  • Executes the contents of a file
     execfile("foo.py")

Note: exec is a statement. eval and execfile are functions

<<< O'Reilly OSCON 2000, Introduction to Python, Slide 89
July 17, 2000, beazley@cs.uchicago.edu
>>>