Python 中的exec、eval、compile

compile(source,filename,mode [,flags [,dont_inherit]])

中文说明:将源编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。

参数source:字符串或者AST(Abstract Syntax Trees)对象。

参数filename:代码文件名称,如果不是从文件读取代码,则传递一些可识别的值。

参数模型:指定编译代码的种类。可以指定为'exec','eval','single'。

参数flag和dont_inherit:这两个参数暂不介绍,可选参数。

摘自 python开发者社区!

 

代码示例:

code  =  """for i in range(10):print(i)"""

comcode  = compile(code,'','exec')

exec  comcode

>>>0 1 2 3 4 5 6 7 8 9

str  = "3 * 4 + 5"

a = compile(str,'','eval')

eval(a)
>>>17

 

  重要栗子

namespace = {'name':"handsome","data": [12, 14, 12, 12],}

code = '''def fun(): return "name%s ,age is%d"%(name, data[3]) '''

func = compile(code, '<string>', "exec")

exec(func,namespace)

result = namespace['fun']()

print(result)

>>>name handsome ,age is12

 



posted @ 2017-03-13 20:04  Jhon23  阅读(171)  评论(0编辑  收藏  举报