python檔案類型的學習筆記

來源:互聯網
上載者:User

一、檔案分類:

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其他版本可能有所不同】

聯繫我們

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