[Dynamic Language] Python Exec & Compile
2010-09-11 17:31
253 查看
动态语言的一个重要特征是直接运行代码字符串。
Python内置函数里,exec 关键字执行多行代码片段,eval() 函数通常用来执行一条包含返回值的表达式,execfile 用来执行源码文件。
exec
Eval
eval() 和 execfile() 都有 "globals, locals" 参数,用于传递环境变量,默认或显式设置为 None 时都直接使用 globals() 和 locals() 获取当前作用域的数据。
execfile
main.py
test.py
输出结果:
将代码编译成字节码
内置函数 compile() 将一段源代码编译成 codeobject,然后可以提交给 exec 执行
compile(source, filename, mode[, flags[, dont_inherit]])
参数 filename 只是用来在编译错误时显式一个标记,无关输出和存储什么事。mode 可以是 "exec"(多行代码组成的代码块)、"eval"(有返回值的单行表达式)、"single"(单行表达式)。
编译单个源文件,在原目录下生成对应的 <filename>.pyc 字节码文件。
批量编译
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 ...
相关文章推荐
- python 中 exec、 eval、 execfile 和 compile 用法
- python compile、eval、exec内建函数
- python re.compile(?P<name>)
- python中eval, exec, execfile,和compile [转载]
- python中eval, exec, execfile,和compile
- python:exec eval execfile compile介绍
- python中eval, exec, execfile,和compile(转载)
- Python之exec()/compile()方法使用
- python中eval, exec, execfile,和compile
- python中eval, exec, execfile,和compile
- python中eval, exec, execfile,和compile
- python中eval, exec, execfile,和compile
- Python可执行对象——exec、eval、compile
- python之exec,eval,execfile,compile
- python中eval, exec, execfile,和compile
- Openwrt编译python3时出现错误:No rule to make target `package//host/compile'
- python中eval, exec, execfile,和compile
- Python可执行对象——exec、eval、compile
- python 中 exec、 eval、 execfile 和 compile 用法
- python eval, exec. compile