内置函数——eval、exec、compile

eval() 将字符串类型的代码执行并返回结果

print(eval('1+2+3+4'))

exec()将自字符串类型的代码执行

print(exec("1+2+3+4"))
exec("print('hello,world')")
code = '''
import os
print(os.path.abspath('.'))
'''
code = '''
print(123)
a = 20
print(a)
'''
a = 10
exec(code,{'print':print},)
print(a)
code = '''
import os
print(os.path.abspath('.'))
'''
code = '''
print(123)
a = 20
print(a)
'''
a = 10
exec(code,{'print':print},)
print(a)

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

参数说明:   

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

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

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

 
>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
1
3
5
7
9 >>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2) >>> #交互语句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name #执行前name变量不存在
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
name
NameError: name 'name' is not defined
>>> exec(compile3) #执行时显示交互命令,提示输入
please input your name:'pythoner'
>>> name #执行后name变量有值
"'pythoner'"

最新文章

  1. Xshell显示中文乱码问题
  2. 轻量级通信引擎StriveEngine —— C/S通信demo(2) —— 使用二进制协议 (附源码)
  3. 【bzoj1085】 SCOI2005—骑士精神
  4. InfoPackage的更新模式
  5. thikphp创建共享数据config.php
  6. 关于 MySQL 的 boolean 和 tinyint(1) (转)
  7. Thrift——初学
  8. JavaScript escape encodeURI encodeURIComponent() 函数
  9. Gulpfile.js——编译、压缩、合并js和css文件
  10. C语言itoa()函数和atoi()函数详解(整数转字符)
  11. css实现响应式全屏背景
  12. ASP.Net IE10 _doPostBack 未定义错误【转】
  13. cocos js响应过程
  14. Unix/Linux &#39;dirctory tree&#39; command.
  15. PAT 团体程序设计天梯赛-练习集 L1-018. 大笨钟
  16. python_缩进_格式化代码
  17. d3实现家族树
  18. 【Keras篇】---利用keras改写VGG16经典模型在手写数字识别体中的应用
  19. shell编程练习(三): 笔试21-30
  20. 使用ThreadPoolExecutor进行多线程编程

热门文章

  1. 【名称解释】#001 IIS名词解释
  2. IKVM.NET入门(2)
  3. js实现svg图形转存为图片下载[转]
  4. python第二十三课——dict中的函数
  5. java基础面试题(JVM篇)
  6. php魔术变量
  7. CVE-2017-8046 复现与分析
  8. 定义抽象类Shape,抽象方法为showArea(),求出面积并显示,定义矩形类Rectangle,正方形类Square,圆类 Circle,根据各自的属性,用showArea方法求出各自的面积,在main方法中构造3个对象,调用showArea方法。(体现多态)
  9. Kafka设计解析(十六)Kafka 0.11消息设计
  10. HDU 1316 (斐波那契数列,大数相加,大数比较大小)