Python生成pyc文件
pyc文件是py文件編譯后生成的字節碼文件(byte code)。pyc文件經過python解釋器最終會生成機器碼運行。所以pyc文件是可以跨平台部署的,類似Java的.class文件。一般py文件改變后,都會重新生成pyc文件。
為什么要手動提前生成pyc文件呢,主要是不想把源代碼暴露出來。
生成單個pyc文件
對於py文件,可以執行下面命令來生成pyc文件。
python -m foo.py
另外一種方式是通過代碼來生成pyc文件。
import py_compile
py_compile.compile('/path/to/foo.py')
批量生成pyc文件
針對一個目錄下所有的py文件進行編譯。python提供了一個模塊叫compileall,具體請看下面代碼:
import compileall
compileall.compile_dir(r'/path')
這個函數的格式如下:
compile_dir(dir[, maxlevels[, ddir[, force[, rx[, quiet]]]]])
參數含義:
- maxlevels: 遞歸編譯的層數
- ddir: If ddir is given, it is prepended to the path to each file being compiled for use in compilation time tracebacks, and is also compiled in to the byte-code file, where it will be used in tracebacks and other messages in cases where the source file does not exist at the time the byte-code file is executed. (誰能翻譯一下( ⊙o⊙?)不懂)
- force: 如果True,不論是是否有pyc,都重新編譯
- rx: 一個正則表達式,排除掉不想要的目錄
- quiet:如果為True,則編譯不會在標准輸出中打印信息
命令行為:
python -m compileall <dir>
@完
參考: