python compile、eval、exec內建函數

來源:互聯網
上載者:User

標籤:python

  1. compile函數

    compile()函數允許程式員在運行時刻迅速產生代碼對象,然後就可以用exec 語句或者內建函

數eval()來執行這些對象或者對它們進行求值。一個很重要的觀點是:exec 和eval()都可以執行字

符串格式的Python 代碼。當執行字串形式的代碼時,每次都必須對這些代碼進行位元組編譯處理。

compile()函數提供了一次性位元組代碼先行編譯,以後每次調用的時候,都不用編譯了。

    compile(source, filename, mode[, flags[, dont_inherit]])    

    第一參數代表了要編譯的python 代碼。第二個字串,雖然是必需的,但通常被置為空白串。mode參數是個字串,它用來表明代碼對象的類型。有三個可能值:

    ‘eval‘ 可求值的運算式[和eval()一起使用]

    ‘single‘ 單一可執行語句[和exec或eval()一起使用]

    ‘exec‘ 可執行語句組[和exec一起使用]

可求值運算式

>>> eval_code = compile(‘100 + 200‘, ‘‘, ‘eval‘)>>> eval(eval_code)300

單一可執行語句

>>> single_code = compile(‘print "Hello world!"‘, ‘‘, ‘single‘)>>> single_code<code object <module> at 0xb76ebd10, file "", line 1>>>> exec single_codeHello world!>>> eval(eval_code)Hello world!

可執行語句組

>>> exec_code = compile("""... req = input(‘Count how many numbers? ‘)... for eachNum in range(req):... print eachNum... """, ‘‘, ‘exec‘)>>> exec exec_codeCount how many numbers? 6012345


2.eval函數

    eval()對錶達式求值,後者可以為字串或內建函數complie()建立的先行編譯代碼對象。

    eval(source[, globals[, locals]])

    第二個和第三個參數,都為可選的,分別代表了全域和局部名字空間中的對象。如果給出這兩個參數,globals 必須是個字典,locals可以是任意的映射對象,比如,一個實現了__getitem__()方法的對象。(在2.4 之前,local 必須是一個字典)如果都沒給出這兩個參數,分別預設為globals()和locals()返回的對象,如果只傳入了一個全域字典,那麼該字典也作為locals 傳入。

>>> eval(‘100 + 200‘)300


3.exec語句

    exec 語句執行代碼對象或字串形式的python 代碼。

    exec obj

    被執行的對象(obj)可以只是原始的字串,比如單一語句或是語句組,它們也可以先行編譯成

一個代碼對象(分別用‘single‘和‘exec"參數)。

>>> exec """... x = 0... print ‘x is currently:‘, x... while x < 5:... x += 1... print ‘incrementing x to:‘, x... """x is currently: 0incrementing x to: 1incrementing x to: 2incrementing x to: 3incrementing x to: 4incrementing x to: 5

    最後, exec 還可以接受有效python 檔案對象。如果我們用上面的多行代碼建立一個叫xcount.py 的檔案,那麼也可以用下面的方法執行相同的代碼

>>> f = open(‘xcount.py‘) # open the file>>> exec f # execute the filex is currently: 0incrementing x to: 1incrementing x to: 2incrementing x to: 3incrementing x to: 4incrementing x to: 5

python compile、eval、exec內建函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.