Python生成pyc文件


Python生成pyc文件
pyc文件是py文件編譯后生成的字節碼文件(byte code)。pyc文件經過python解釋器最終會生成機器碼運行。所以pyc文件是可以跨平台部署的,類似Java的.class文件。一般py文件改變后,都會重新生成pyc文件。

為什么要手動提前生成pyc文件呢,主要是不想把源代碼暴露出來。

生成單個pyc文件
對於py文件,可以執行下面命令來生成pyc文件。

python -m foo.py
1
另外一種方式是通過代碼來生成pyc文件。

import py_compile
py_compile.compile('/path/to/foo.py')
1
2
批量生成pyc文件
針對一個目錄下所有的py文件進行編譯。python提供了一個模塊叫compileall,具體請看下面代碼:

import compileall
compileall.compile_dir(r'/path')
1
2
這個函數的格式如下:

compile_dir(dir[, maxlevels[, ddir[, force[, rx[, quiet]]]]])
1
參數含義:
- 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>
1
@完

參考:
- http://www.cnblogs.com/dkblog/archive/2009/04/16/1980757.html
- https://docs.python.org/2/library/compileall.html
- https://docs.python.org/3/library/compileall.html
- http://blog.csdn.net/loveyilili/article/details/12567729
---------------------
作者:kriszhang
來源:CSDN
原文:https://blog.csdn.net/kriszhang/article/details/68947242
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM