Python exec 内置语句
描述
exec 执行储存在字符串或文件中的Python语句,相比于 eval,exec可以执行更复杂的 Python 代码。
需要说明的是在 Python2 中exec不是函数,而是一个内置语句(statement),但是Python 2中有一个 execfile() 函数。可以理解为 Python 3 把 exec 这个 statement 和 execfile() 函数的功能够整合到一个新的 exec() 函数中去了。
语法
参数
实例
实例 1
>>>exec 'print "Hello World"'Hello World# 单行语句字符串>>> exec "print 'runoob.com'"runoob.com# 多行语句字符串>>> exec """for i in range(5):... print "iter time: %d" % i... """iter time: 0iter time: 1iter time: 2iter time: 3iter time: 4
实例 2
x = 10expr = """z = 30sum = x + y + zprint(sum)"""def func():y = 20exec(expr)exec(expr, {'x': 1, 'y': 2})exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})func()
输出结果:
603334
