exec eval compile區(qū)別:
exec 執(zhí)行python代碼,無論是存儲在對象/文件/字符串內(nèi)都可執(zhí)行
eval 執(zhí)行存儲于對象或字符串內(nèi)的python表達(dá)式
compile 對代碼預(yù)編譯,可防止重復(fù)編譯一段代碼
exec
格式:exec obj
代碼:
>>> exec '''for i in range(3):
... print i
... '''
0
1
2
eval
格式:eval( obj[, globals=globals(), locals=locals()] ) 全局變量和局部變量
代碼:
>>> a = 2
>>> eval('a * 5')
10
compile
格式:compile( str, file, type) file代碼存放地方 type有三類:eval single配合單一語句exec使用 exec配合exec多語句使用
代碼:
# 執(zhí)行python表達(dá)式
>>> eval_code = compile('3 * 4', '', 'eval')
>>> eval(eval_code)
12
# 執(zhí)行python單一語句
>>> single_code = compile('print "hello word!"', '', 'single')
>>> exec(single_code)
hello word!
# 執(zhí)行python多條語句
>>> exec_code = compile("""for i in range(5):
... print i""", '', 'exec')
>>> exec(exec_code)
0
1
2
3
4