内置函数:exec、eval、compile

eval:将字符串内的代码执行,有返回值,用于简单的计算
exec:将字符串内的代码执行,没有返回值,用于简单的逻辑判断
   均可以读取文件进行执行
info_str = '1+2+3'
couunt = eval(info_str)
couunt1 = exec(info_str)
print(couunt)#返回6
print(couunt1)#无返回值

jud ='''
def func(a,b):
    return a if a>b else b
func(1,2)
'''
exec(jud)#无返回值

jud1 ='''
for i in range(10):
    print(i)
'''
exec(jud1)#返回0-9
compile:将源代码编译成可以由exec()或eval()执行的代码对象。源代码可以表示Python模块、语句或表达式。'single'编译单个(交互的)语句

code = '1+2+3'
cpe = compile(code,'','eval')
print(eval(cpe))

code = 'for i in range(10):print(i)'
cpe = compile(code,'','exec')
exec(cpe)

code = 'name = input("请输入你的姓名:")'
cpe = compile(code,'','single')
# print(name)#未输入,执行报错
exec(cpe)#执行代码,输入name
print(name)#语句报错,但执行时不会报错,并能够获取输入的值
 
原文地址:https://www.cnblogs.com/aizhinong/p/11404132.html