exec 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码。
以下是 exec 的语法:
exec(object[, globals[, locals]])
exec 返回值永远为 None。
以下展示了使用 exec 的实例:
>>>exec('print("Hello World")')
Hello World # 单行语句字符串
exec("print ('dida100.com')")
dida100.com #  多行语句字符串
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
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()
输出结果:
60 33 34