Python中exec的使用
时间:2014-03-02 08:23:54
收藏:0
阅读:501
exec语句
exec语句用来执行储存在字符串或者文件中的python语句。可以生成一个包含python代码的字符串,然后使用exec语句执行这些语句。
>>>exec ‘print "hello word"‘ hello world
exec语句的用法和eval_r(),execfile()是不一样的,exec是一个语句,而eval_r()和execfile()是内建函数。
>>>class FUN:
.....: def __init__(self,mystring):
.....: exec("self." + mystring)
>>>f = FUN("age = 11")
>>>print f.age
11
eval语句
eval(str [,globals [,locals ]]) #函数将字符串str当成有效Python表达式来求值,并返回计算结果。例如
>>>eval(‘2*3‘) 6
execfile函数
execfile(filename [,globals [,locals ]])函数可以用来执行一个文件。
execfile(‘c:\execmypython.py‘)
当全局变量和局部变量
默认的,eval(),exec,execfile()所运行的代码都位于当前的名字空间中。
eval(), exec,和 execfile()函数也可以接受一个或两个可选字典参数作为代码执行的全局名字空间和局部名字空间.
例如:
>>>globals = {‘x‘:7,
.....: ‘y‘:10,
.....: ‘names‘:[‘aa‘,‘bb‘,‘cc‘]
.....: }
>>>locals = {}
>>>a = eval("3*x+4*y",globals,locals)
>>>print a
61
>>>exec("for i in names: print i",globals,locals)
aa
bb
cc
原文:http://blog.csdn.net/magicharvey/article/details/20214563
评论(0)