Python可執行對象——exec、eval、compile

來源:互聯網
上載者:User

標籤:注意   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.