python标准库-builtin 模块之compile,execfile
eval函数仅仅允许执行简单的表达式。对于更大的代码块时,使用compile和exec函数。
例子:使用 compile函数验证语法
NAME = "script.py"
BODY = """
prnt 'owl-stretching time'
"""
try:
compile(BODY, NAME, "exec")
except SyntaxError, v:
print "syntax error:", v, "in", NAME
结果如下:
syntax error: invalid syntax in script.py
当成功时,compile函数返回一个代码对象,你能够使用exec来执行他。
BODY = """
print 'the ant, an introduction'
"""
code = compile(BODY, "
浙公网安备 33010602011771号