您的位置:首页 > 编程语言 > Python开发

python小点心--compile

2016-02-22 19:09 633 查看
函数原型: compile(source, filename, mode[, flags[, dont_inherit]])

简单讲,就是把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就可以访问他们
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: