- Python: compile, exec or eval
- compile()
- exec(object[, globals[, locals]])
- eval(expression[, globals[, locals]])
- 举例
Assign: smart dengc4r
Status: Completed compile()
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
主要作用是将source编译成代码或者ast对象,代码对象可以被exec() 或者eval()执行,source可以是常规的字符串、字节字符串,或者是ast对象。
AST又叫做抽象语法树,ast模块帮助python程序处理python语法的抽象语法树,该模块能能够帮助理解当前语法在编程层面的样貌。
filename实参需要是代码读取的文件名,如果代码不需要从文件读取,可以传入一些可辨识的值(经常是用’’。
mode 实参指定编译代码必须使用的模式,如果soruce是语句序列,可以是 exec;如果是单一表达式,可以是eval;如果是单个交互 语句,可以是single
exec(object[, globals[, locals]])将exec语句转换为exec()函数调用。
eval(expression[, globals[, locals]])实参是一个字符串,以及可选的globals和locals,globals实参是一个字典,locals可以是任意映射对象。
>>> x = 1
>>> eval('x+1')
2
该函数还可以用于执行任意代码(比如compile()创建的对象),这时传入的是代码对象,而非一个字符串,如果代码对象已用参数为mode的‘exec’进行了编译,那么eval的返回值将为None。
提示:exec()函数支持语句的动态执行,globals 和 locals函数分别返回当前的全局和本地字典。
举例# 这里定义了一个code 的字符串
# 里面的内容就是一个TestCompile的对象,有一个message的属性
# 一个__init__的方法,还有一个print的方法
# 最后就是一个程序的入口,调用了print方法
code = """
class TestCompile(object):
message = "hello world"
def __init__(self, code=None):
self.code = code
@classmethod
def print(self):
print(self.message)
if __name__ == '__main__':
TestCompile().print()
"""
# 这里动态编译了这段code
binary = compile(code, '', 'exec')
# 申明一个全局的dit
dit = globals().copy()
# 最后执行code
exec(binary, dit)
print("end")
下面是最后的输出结果:
Connected to pydev debugger (build 203.7717.81) hello world end Process finished with exit code 0
总结来说就是compile将静态代码编译成相应的对象,然后使用exec 或者是eval动态加载



