python中编译pyc的方法
這篇文章主要介紹了python中編譯pyc的方法,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
Python生成pyc文件
pyc文件是py文件編譯后生成的字節碼文件(byte code)。pyc文件經過python解釋器最終會生成機器碼運行。所以pyc文件是可以跨平臺部署的,類似Java的.class文件。一般py文件改變后,都會重新生成pyc文件。
為什么要手動提前生成pyc文件呢,主要是不想把源代碼暴露出來。
生成單個pyc文件
對于py文件,可以執行下面命令來生成pyc文件。
python-mfoo.py
另外一種方式是通過代碼來生成pyc文件。
importpy_compile
py_compile.compile('/path/to/foo.py')
批量生成pyc文件
針對一個目錄下所有的py文件進行編譯。python提供了一個模塊叫compileall,具體請看下面代碼:
importcompileall 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.
- force:如果True,不論是是否有pyc,都重新編譯
- rx:一個正則表達式,排除掉不想要的目錄
- quiet:如果為True,則編譯不會在標準輸出中打印信息
命令行為:
python-mcompileall<dir>
總結
以上是生活随笔為你收集整理的python中编译pyc的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: X20plus怎么链接电脑
- 下一篇: JAVA面试题集收藏大放送