其實很簡單,
用
python -m py_compile file.py
python -m py_compile /root/src/{file1,file2}.py
編譯成pyc文件。
也可以寫份腳本來做這事:
Code:
import py_compile py_compile.compile('path') //path是包括.py文件名的路徑 |
用
python -O -m py_compile file.py
編譯成pyo文件。
1.其中的 -m 相當於腳本中的import,這里的-m py_compile 相當於上面的 import py_compile
2.-O 如果改成 -OO 則是刪除相應的 pyo文件,具體幫助可以在控制台輸入 python -h 查看
生成單個pyc文件
python就是個好東西,它提供了內置的類庫來實現把py文件編譯為pyc文件,這個模塊就是 py_compile 模塊。
使用方法非常簡單,如下所示,直接在idle中,就可以把一個py文件編譯為pyc文件了。(假設在windows環境下)
import py_compile
py_compile.compile(r'H:\game\test.py')
compile函數原型:
compile(file[, cfile[, dfile[, doraise]]])
file 表示需要編譯的py文件的路徑
cfile 表示編譯后的pyc文件名稱和路徑,默認為直接在file文件名后加c 或者 o,o表示優化的字節碼
dfile 這個參數英文看不明白,請各位大大賜教。(鄙視下自己)原文:it is used as the name of the source file in error messages instead of file
doraise 可以是兩個值,True或者False,如果為True,則會引發一個PyCompileError,否則如果編譯文件出錯,則會有一個錯誤,默認顯示在sys.stderr中,而不會引發異常
(來自python2.5文檔)
批量生成pyc文件
一般來說,我們的工程都是在一個目錄下的,一般不會說僅僅編譯一個py文件而已,而是需要把整個文件夾下的py文件都編譯為pyc文件,python又為了我們提供了另一個模塊:compileall 。使用方法如下:
import compileall
compileall.compile_dir(r'H:\game')
也可以直接用命令行編譯一個目錄下的文件,如:# python -m compileall /root/src/
這樣就把game目錄,以及其子目錄下的py文件編譯為pyc文件了。嘿嘿,夠方便吧。來看下compile_dir函數的說明:
compile_dir(dir[, maxlevels[, ddir[, force[, rx[, quiet]]]]])
dir 表示需要編譯的文件夾位置
maxlevels 表示需要遞歸編譯的子目錄的層數,默認是10層,即默認會把10層子目錄中的py文件編譯為pyc
ddir 英文沒明白,原文:it is used as the base path from which the filenames used in error messages will be generated。
force 如果為True,則會強制編譯為pyc,即使現在的pyc文件是最新的,還會強制編譯一次,pyc文件中包含有時間戳,python編譯器會根據時間來決定,是否需要重新生成一次pyc文件
rx 表示一個正則表達式,比如可以排除掉不想要的目錄,或者只有符合條件的目錄才進行編譯
quiet 如果為True,則編譯后,不會在標准輸出中,打印出信息