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

[Dynamic Language] Python Exec & Compile

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

>>> code = """
... def test():
...     print "this is a test by abeen"
... """
>>> test() # 'test'is not defined
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined
>>> exec code
>>> test() # test()成功执行
this is a test by abeen


Eval
eval() 和 execfile() 都有 "globals, locals" 参数,用于传递环境变量,默认或显式设置为 None 时都直接使用 globals() 和 locals() 获取当前作用域的数据。

>>> a =10
>>> eval("a+3") #默认传递环境变量
13
>>> evla("a+3")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'evla' is not defined
>>> eval("a+3")
13
>>> eval("a+3",{},{"a":100}) #显示传递环境变量
103


execfile
main.py

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

s = "main.s"
execfile("test.py")


test.py

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

def test():
print "this is a test by abeen", s

test()


输出结果:

abeen@localhost:~/learn_test/exec_compile$ python main.py
this is a test by abeen main.s


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

>>> source = """
... def test():
...     print "this is a test by abeen"
...
... """
>>> code = compile(source, "test.py", "exec")
>>> exec code
>>> test()
this is a test by abeen


编译单个源文件,在原目录下生成对应的 <filename>.pyc 字节码文件。

>>> import py_compile
>>> py_compile.compile("test.py")


批量编译

>>> import compileall
>>> compileall.compile_dir("./")
Listing ./ ...
Compiling ./main.py ...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: