一、檔案分類:
1)*.py檔案,這就是我們常見的py源檔案,沒什麼好說的;
2)*.pyc, py源檔案編譯成的二進位位元組碼檔案,依然由python載入執行,不過速度會提高,也會隱藏源碼;
3)*.pyo,最佳化編譯後的程式,也是二進位檔案,適用於嵌入式系統。
二、產生pyc和pyo檔案
1)如何產生pyc檔案呢?
假設我們有一個1.py檔案需要編譯成pyc檔案,則在python shell輸入
import py_compile
py_compile.compile('1.py')
這樣就可以產生pyc檔案了
2)如何產生pyo檔案呢?
python -O -m py_compile 1.py
另外,pyc和pyo跟py檔案是一樣的,依然可以用python 1.pyc等形式執行
python原始碼的檔案以py為副檔名,由python程式解釋,不需要編譯,以下為hello.py的代碼
[root@AY130704092906278009Z python]# cat hello.py
#!/usr/bin/python
print("hello world")
位元組代碼
python源檔案經編譯後產生的副檔名為pyc的檔案
寫一個python程式去編譯上面的hello.py代碼:(2.py程式碼如下)
[root@AY130704092906278009Z python]# cat 2.py
import py_compile
py_compile.compile('hello.py')
運行python 2.py可以看到產生了一個__pycache__檔案夾,下面有一個pyc檔案,那個檔案也可以直接執行
[root@AY130704092906278009Z python]# python 2.py
[root@AY130704092906278009Z python]# ls
2.py hello.py reference.py str_methods.py using_list.py
code __pycache__ seq.py using_dict.py using_tuple.py
代碼最佳化
經過最佳化的源檔案,擴民名為.pyo
運行:
python -O -m py_compile hello.py,同樣他也產生在__pycache__檔案夾下。
[root@AY130704092906278009Z python]# cd __pycache__/
[root@AY130704092906278009Z __pycache__]# ls
hello.cpython-33.pyc hello.cpython-33.pyo
[root@AY130704092906278009Z __pycache__]# python hello.cpython-33.pyc
hello world
[root@AY130704092906278009Z __pycache__]# python hello.cpython-33.pyo
hello world
上面三種就是python的三種檔案格式。【以上均基於python3.3上啟動並執行結果,python其他版本可能有所不同】