python小点心--compile
2016-02-22 19:09
633 查看
函数原型: compile(source, filename, mode[, flags[, dont_inherit]])
简单讲,就是把source编译成可执行的代码
比如有一个python脚本compileDemo1.py,内容为:
那么我们可以在目录下新建一个脚本,内容为:
compileDemo1.py 中的代码是可以直接执行的,那么脚本内的类和函数如何使用呢?
新建脚本compileDemo3.py,内容为:
在目录下新建一个脚本,内容为:
运行脚本,会调用compileDemo3.py中的fun函数,生成了一个Test的对象并调用myprint方法
exec c in globals()这条语句很关键,它将编译好的类和函数存入到了全局变量,这样,通过globals就可以访问他们
简单讲,就是把source编译成可执行的代码
比如有一个python脚本compileDemo1.py,内容为:
#coding=utf-8 ''' Created on 2016-2-16 @author: Administrator ''' addr = '192.168.1.1' print addr
那么我们可以在目录下新建一个脚本,内容为:
#coding=utf-8 ''' Created on 2016-2-16 @author: Administrator ''' filepath = './compileDemo1.py' with open(filepath, 'r') as f: text = f.read() c = compile(text,'success','exec') # 编译为字节代码对象 exec c这时,就会打印出192.168.1.1
compileDemo1.py 中的代码是可以直接执行的,那么脚本内的类和函数如何使用呢?
新建脚本compileDemo3.py,内容为:
#coding=utf-8 ''' Created on 2016-2-16 @author: Administrator ''' class Test(): def myprint(self): print 'ok' def fun(): print 'fun' if __name__ == '__main__': print 'main'
在目录下新建一个脚本,内容为:
#coding=utf-8 ''' Created on 2016-2-16 @author: Administrator ''' filepath = './compileDemo3.py' with open(filepath, 'r') as f: text = f.read() c = compile(text,'success','exec') # 编译为字节代码对象 exec c in globals() ind_obj = globals()['Test']() ind_obj.myprint() globals()['fun']()
运行脚本,会调用compileDemo3.py中的fun函数,生成了一个Test的对象并调用myprint方法
exec c in globals()这条语句很关键,它将编译好的类和函数存入到了全局变量,这样,通过globals就可以访问他们
相关文章推荐
- [python]decimal常用操作和需要注意的地方
- 用python3.x正则表达式匹配中文字符串
- 【python】 字符串替换+正则
- python之requests-multipart/from-data
- Xgboost + python Win7 安装
- python基础学习八: 界面设计基础
- selenium + python自动化测试环境搭建--亲测
- python 面向对象 初级
- python内置模块(三)
- Python正则表达式指南
- wxpython实现文件拖拽
- python下一个转码的问题
- Python 字符编码判断
- Python多版本共存之pyenv
- Python中*args 和**kwargs的用法
- libsvm+python配置
- Python2.7 with MySQL Connector/Python Sample(Windows OS)
- Python——运算符重载(1)
- python生成二维码
- python--knn算法练习