动态语言的一个重要特征是直接运行代码字符串。
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
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
# !/usr/bin/env python
# _*_ coding:utf-8 _*_
s = " main.s "
execfile( " 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
1 >>> import py_compile
2 >>> py_compile.compile( " test.py " )
1 >>> import compileall
2 >>> compileall.compile_dir( " ./ " )
3 Listing . / ...
4 Compiling . / main.py ...