eval(), exec, execfile(), and compile()
The eval(str [,globals [,locals]]) function executes an expression string and returns the result. For example:
a = eval('3*math.sin(3.5+x) + 7.2')
Similarly, the exec statement executes a string containing arbitrary Python code. The code supplied to exec is executed as if the code actually appeared in place of the exec statement. For example:
a = [3, 5, 10, 13] exec "for i in a: print i"
Finally, the execfile(filename [,globals [,locals]]) function executes the contents of a file. For example:
execfile("foo.py")
All these functions execute within the namespace of the caller (which is used to resolve any symbols that appear within a string or file). Optionally, eval(), exec, and execfile() can accept ...
Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.