Python exec built-in statement
Description
exec executes Python statements stored in a string or file. Compared to eval, exec can execute more complex Python code.
It should be noted that in Python 2, exec is not a function but a built-in statement. However, Python 2 has an execfile() function. It can be understood that Python 3 integrated the functionality of the exec statement and the execfile() function into a new exec() function.
Syntax
The following is the syntax of exec:
exec obj
Parameters
- obj -- The expression to be executed.
Return Value
The return value of exec is always None.
Examples
The following shows examples using exec:
Example 1
>>>exec 'print "Hello World"'
Hello World
# Single-line statement string
>>> exec "print 'example.com'"
example.com
# Multi-line statement string
>>> exec """for i in range(5):
... print "iter time: %d" % i
... """
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4
Example 2
x = 10
expr = """
z = 30
sum = x + y + z
print(sum)
"""
def func():
y = 20
exec(expr)
exec(expr, {'x': 1, 'y': 2})
exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})
func()
Output result:
60 33 34Other Extensions
Python Built-in Functions