eval exec compile

eval() exec() compile()

eval():执行一个字符串表达式,并返回表达式的值

exec():执行一个字符串表达式,没有返回值

exec('print(123)')
eval('print(123)')
print(eval('1+2+3+4'))   # 有返回值
print(exec('1+2+3+4'))   #没有返回值
'''
123
123
10
None
'''

compile():将一个字符串编译为字节代码

compile(source, filename, mode)

1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  

2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  

3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。

code1 = 'for i in range(0,10): print (i)'
compile1 = compile(code1,'','exec')
exec(compile1)

code2 = '1 + 2 + 3 + 4'
compile2 = compile(code2,'','eval')
print(eval(compile2))

code3 = 'name = input("please input your name:")'
compile3 = compile(code3,'','single')
exec(compile3) #执行时显示交互命令,提示输入
print(name)
name #执行后name变量有值
"'pythoner'"

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值