内置函数— — eval、exec、compile

字符串类型代码:eval、exec、compile

eval()  执⾏字符串类型的代码,并返回最终结果

print(eval("2+2")) # 4 
n=8
print(eval("2+n")) # 10
def func():
    print(666)
eval("func()")  # 666

# 简易计算器
code = input("请输入你要执行的代码:")
ret = eval(code)
print(ret)
>>>请输入你要执行的代码:1+2  + 3
>>>6


# 把字符串类型的代码还原回字典, 列表, 元组
s = "{'name':'alex', 'age':18, 'isMan':False}" # 字符串
ret = eval(s)  # 侧重的有返回值
print(ret)  # {'name': 'alex', 'age': 18, 'isMan': False}
print(type(ret))  # <class 'dict'>

exec()  执⾏字符串类型的代码,返回值永远为 None. (execute执行的缩写)

# 相比于 eval,exec可以执行更复杂的 Python 代码,但是也不能太长,不能太乱(那种要使用compile)
# 流程控制语句
exec("""
for i in range(10):
    print(i)
""")
# 自定义函数
exec("""
def func():
    print("我是周杰伦") 
func()
""")


print(exec("1+2+3+4"))  # None 没有返回值. 想要返回值用eval
exec("print('hello,world')")  # hello,world


code = input("请输入你要执行的代码")
a = exec(code) # 没有返回值. 想要返回值用eval
print(a)
>>>请输入你要执行的代码1+2  + 3
>>>None

code = input("请输入你要执行的代码")
exec(code) # 没有返回值. 想要返回值用eval
print(a)   # pycharm报错不一定准
# 这里的代码a在pycharm中是出红线了,因为它不知道这里的a是什么,上面的代码没有定义过.但是代码执行
之后在控制台输出了正确的结果并没有报错,因为你在input函数执行时候的控制台中输入了a = 'alex'(反正就是以代码(字符串)的形式创建并赋值了变量a)
>>>请输入你要执行的代码a = 'alex' >>>alex

compile  将字符串类型的代码编译成字节代码对象。代码对象能够通过exec语句来执行或者eval()进行求值。

语法: 

compile(source, filename, mode[, flags[, dont_inherit]])
参数说明:

  1. 参数source:要执⾏的代码, 动态代码⽚段

 

 2. 参数 filename文件名, 代码存放的文件名, 当传入了第一个参数的时候, 这个参数给空字符串就可以了代码要么直接以字符串代码的形式给出,要么存
    放在文件中给出,所以这两个参数必须有一个为空字符串.
  3. 参数model:模式,指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。
    exec: 当source中包含流程语句时,model应指定为‘exec’;
    eval:  当source中只包含一个简单的求值表达式,model应指定为‘eval’;
    single: 当source中包含了交互式命令语句,model应指定为'single'。

#流程语句使用exec
code1 = "for i in range(10): print(i)"  #代码
c1 = compile(code1, "", mode="exec") # 预加载代码
exec(c1)  # 运行代码  # 字符串代码内部存在print就不需要再print了
>>>
0
1
2
3
4
5
6
7
8
9


#简单求值表达式用eval
code2 = "1+2+3"
c2 = compile(code2, "", mode="eval")
a = eval(c2)
print(a)
>>>
6


#交互语句(比如input)用single
code3 = "name = input('请输⼊入你的名字:')"
c3 = compile(code3, "", mode="single")
exec(c3)  
print(name)  # 字符串代码内部不存在print就需要再print
>>> print(name)#执行前name变量不存在,解释器红线报错
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    name
NameError: name 'name' is not defined
>>> #执行时显示交互命令,提示输入
请输⼊入你的名字:Mary

>>> print(name) #执行后name变量有值,输出
Mary

小结:

  有返回值的字符串形式的代码⽤eval().

  没有返回值的字符串形式的代码用exec().

  一般很少⽤到compile()















 
原文地址:https://www.cnblogs.com/lyfstorm/p/10110920.html