標籤:注意 pil red too com 單行 法語 檔案 代碼
Python提供的調用可執行對象的內建函數進行說明,涉及exec、eval、compile三個函數。exec語句用來執行儲存在代碼對象、字串、檔案中的Python語句,eval語句用來計算儲存在代碼對象或字串中的有效Python運算式,而compile語句則提供了位元組編碼的先行編譯。
當然,需要注意的是,使用exec和eval一定要注意安全性問題,尤其是網路環境中,可能給予他人執行非法語句的機會。
1.exec
格式:exec obj
obj對象可以是字串(如單一語句、語句塊),檔案對象,也可以是已經由compile先行編譯過的代碼對象。
下面是相應的例子:
Python可執行對象之exec使用舉例Python
| 12345678910111213 |
# 單行語句字串>>> exec "print ‘pythoner.com‘"pythoner.com # 多行語句字串>>> exec """for i in range(5):... print "iter time: %d" % i... """iter time: 0iter time: 1iter time: 2iter time: 3iter time: 4 |
代碼對象的例子放在第3部分一起講解。
2.eval
格式:eval( obj[, globals=globals(), locals=locals()] )
obj可以是字串對象或者已經由compile編譯過的代碼對象。globals和locals是可選的,分別代表了全域和局部名稱空間中的對象,其中globals必須是字典,而locals是任意的映射對象。
下面仍然舉例說明:
Python可執行對象之evalPython
| 123 |
>>> x = 7>>> eval( ‘3 * x‘ )21 |
3.compile
格式:compile( str, file, type )
compile語句是從type類型(包括’eval‘: 配合eval使用,’single‘: 配合單一語句的exec使用,’exec‘: 配合多語句的exec使用)中將str裡面的語句建立成代碼對象。file是代碼存放的地方,通常為”。
compile語句的目的是提供一次性的位元組碼編譯,就不用在以後的每次調用中重新進行編譯了。
還需要注意的是,這裡的compile和Regex中使用的compile並不相同,儘管用途一樣。
下面是相應的舉例說明:
Python可執行對象之compilePython
| 12345678910111213141516171819202122 |
>>> eval_code = compile( ‘1+2‘, ‘‘, ‘eval‘)>>> eval_code<code object <module> at 0142ABF0, file "", line 1>>>> eval(eval_code)3 >>> single_code = compile( ‘print "pythoner.com"‘, ‘‘, ‘single‘ )>>> single_code<code object <module> at 01C68848, file "", line 1>>>> exec(single_code)pythoner.com >>> exec_code = compile( """for i in range(5):... print "iter time: %d" % i""", ‘‘, ‘exec‘ )>>> exec_code<code object <module> at 01C68968, file "", line 1>>>> exec(exec_code)iter time: 0iter time: 1iter time: 2iter time: 3iter time: 4 |
Python可執行對象——exec、eval、compile