[Dynamic Language] Python Exec & Compile

动态语言的一个重要特征是直接运行代码字符串。
Python内置函数里,exec 关键字执行多行代码片段,eval() 函数通常用来执行一条包含返回值的表达式,execfile 用来执行源码文件。
exec

1 >>> code = """
2 ... def test():
3 ... print "this is a test by abeen"
4 ... """
5  >>> test() # 'test'is not defined
6 Traceback (most recent call last):
7 File "<stdin>", line 1, in <module>
8 NameError: name 'test' is not defined
9 >>> exec code
10 >>> test() # test()成功执行
11 this is a test by abeen
Eval
eval() 和 execfile() 都有 "globals, locals" 参数,用于传递环境变量,默认或显式设置为 None 时都直接使用 globals() 和 locals() 获取当前作用域的数据。
1 >>> a =10
2 >>> eval("a+3") #默认传递环境变量
3 13
4 >>> evla("a+3")
5 Traceback (most recent call last):
6 File "<stdin>", line 1, in <module>
7 NameError: name 'evla' is not defined
8 >>> eval("a+3")
9 13
10 >>> eval("a+3",{},{"a":100}) #显示传递环境变量
11 103
execfile
main.py

#!/usr/bin/env python
#
_*_ coding:utf-8 _*_

s
= "main.s"
execfile(
"test.py")
test.py
1 #!/usr/bin/env python
2 # _*_ coding:utf-8 _*_
3
4 def test():
5 print "this is a test by abeen", s
6
7 test()
输出结果:
1 abeen@localhost:~/learn_test/exec_compile$ python main.py
2 this is a test by abeen main.s

将代码编译成字节码
内置函数 compile() 将一段源代码编译成 codeobject,然后可以提交给 exec 执行
compile(source, filename, mode[, flags[, dont_inherit]])
参数 filename 只是用来在编译错误时显式一个标记,无关输出和存储什么事。mode 可以是 "exec"(多行代码组成的代码块)、"eval"(有返回值的单行表达式)、"single"(单行表达式)。

1 >>> source = """
2 ... def test():
3 ... print "this is a test by abeen"
4 ...
5 ... """
6 >>> code = compile(source, "test.py", "exec")
7 >>> exec code
8 >>> test()
9 this is a test by abeen
编译单个源文件,在原目录下生成对应的 <filename>.pyc 字节码文件。
1 >>> import py_compile
2 >>> py_compile.compile("test.py")
批量编译

1 >>> import compileall
2 >>> compileall.compile_dir("./")
3 Listing ./ ...
4 Compiling ./main.py ...

 

posted @ 2010-09-11 17:31  ABeen  阅读(1397)  评论(2编辑  收藏  举报