Python可执行对象——exec、eval、compile
Python提供的调用可执行对象的内建函数进行说明,涉及exec、eval、compile三个函数。exec语句用来执行存储在代码对象、字符串、文件中的Python语句,eval语句用来计算存储在代码对象或字符串中的有效的Python表达式,而compile语句则提供了字节编码的预编译。
当然,需要注意的是,使用exec和eval一定要注意安全性问题,尤其是网络环境中,可能给予他人执行非法语句的机会。
1.exec
格式:exec obj
obj对象可以是字符串(如单一语句、语句块),文件对象,也可以是已经由compile预编译过的代码对象。
下面是相应的例子:
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
 | 
 # 单行语句字符串 
>>> exec "print 'pythoner.com'" 
pythoner.com 
#  多行语句字符串 
>>> exec """for i in range(5): 
...   print "iter time: %d" % i 
... """ 
iter time: 0 
iter time: 1 
iter time: 2 
iter time: 3 
iter time: 4 
 | 
代码对象的例子放在第3部分一起讲解。
2.eval
格式:eval( obj[, globals=globals(), locals=locals()] )
obj可以是字符串对象或者已经由compile编译过的代码对象。globals和locals是可选的,分别代表了全局和局部名称空间中的对象,其中globals必须是字典,而locals是任意的映射对象。
下面仍然举例说明:
| 
 1 
2 
3 
 | 
 >>> x = 7 
>>> eval( '3 * x' ) 
21 
 | 
3.compile
格式:compile( str, file, type )
compile语句是从type类型(包括’eval': 配合eval使用,’single': 配合单一语句的exec使用,’exec': 配合多语句的exec使用)中将str里面的语句创建成代码对象。file是代码存放的地方,通常为”。
compile语句的目的是提供一次性的字节码编译,就不用在以后的每次调用中重新进行编译了。
还需要注意的是,这里的compile和正则表达式中使用的compile并不相同,尽管用途一样。
下面是相应的举例说明:
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
 | 
 >>> eval_code = compile( '1+2', '', 'eval') 
>>> eval_code 
<code object <module> at 0142ABF0, file "", line 1> 
>>> eval(eval_code) 
3 
>>> single_code = compile( 'print "pythoner.com"', '', 'single' ) 
>>> single_code 
<code object <module> at 01C68848, file "", line 1> 
>>> exec(single_code) 
pythoner.com 
>>> exec_code = compile( """for i in range(5): 
...   print "iter time: %d" % i""", '', 'exec' ) 
>>> exec_code 
<code object <module> at 01C68968, file "", line 1> 
>>> exec(exec_code) 
iter time: 0 
iter time: 1 
iter time: 2 
iter time: 3 
iter time: 4 
  | 
                    
                
                
            
        
浙公网安备 33010602011771号