Python exec内置函数语句

描述:

exec 执行储存在字符串或文件中的Python语句,相比于 eval,exec可以执行更复杂的 Python 代码。

需要说明的是在 Python2 中exec不是函数,而是一个内置语句(statement),但是Python 2中有一个 execfile() 函数。可以理解为 Python 3 把 exec 这个 statement 和 execfile() 函数的功能够整合到一个新的 exec() 函数中去了。

以下例子是python3中的。

例子1:

exec('print("Hello World")')

输出结果:Hello World

例子2:

exec("print ('runoob.com')")

输出结果:runoob.com

例子3:

a = """for i in range(5):
print ("iter time: %d" % i)"""
exec(a)

输出结果:iter time: 0

iter time: 1
iter time: 2
iter time: 3
iter time: 4


原文地址:https://www.cnblogs.com/pygo/p/12332071.html