1. 程式人生 > >python中pyc和pyo的作用

python中pyc和pyo的作用

    pyc檔案,是python編譯後的位元組碼(bytecode)檔案。只要你運行了py檔案,python編譯器就會自動生成一個對應的pyc位元組碼檔案。這個pyc位元組碼檔案,經過python直譯器,會生成機器碼執行(這也是為什麼pyc檔案可以跨平臺部署,類似於java的跨平臺,java中JVM執行的位元組碼檔案)。下次呼叫直接呼叫pyc,而不呼叫py檔案。直到你這個py檔案有改變。python直譯器會檢查pyc檔案中的生成時間,對比py檔案的修改時間,如果py更新,那麼就生成新的pyc。

    pyo檔案,是python編譯優化後的位元組碼檔案。pyo檔案在大小上,一般小於等於pyc檔案。如果想得到某個py檔案的pyo檔案,可以這樣:

    python -O -m py_compile xxxx.py

    python文件是這樣描述的:這個優化沒有多大作用,只是移除了斷言。原文如下:

    When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in .pyo files. The optimizer currently doesn’t help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.

    至於速度,執行幾乎一樣,載入pyc和pyo稍佔優勢。python文件是這樣說的:   

    A program doesn’t run any faster when it is read from a .pyc or .pyo file than when it is read from a .py file; the only thing that’s faster about .pyc or .pyo files is the speed with which they are loaded.

    最後貼一張 py pyc pyo 的檔案對比圖。