將 Python 項目的所有py文件編譯成.pyc


實例地址源碼地址:https://gitee.com/mzfly/py-dist

Python 項目編譯成.pyc。

compile.py 是示例,

將 compile.py 放到項目根目錄,

編輯main方法的copyfile和copytree列表,

設置所在目錄對應要編譯的文件和目錄,

最后執行 main 方法后(即執行命令:python compile.py),

所在目錄將生成一個dist目錄,

里面就是編譯后的文件。

compile.py源碼如下:

# compile.py
import
compileall import shutil import os current_dir = os.path.dirname(os.path.abspath(__file__)) dist_dir = current_dir + r"\dist" def mk_dist(copyfile=None, copytree=None): try: if os.path.exists(dist_dir): shutil.rmtree(dist_dir) os.mkdir(dist_dir) if copyfile: for filename in copyfile: shutil.copyfile(filename, dist_dir + '\\' + filename) if copytree: for dirname in copytree: shutil.copytree(dirname, dist_dir + '\\' + dirname) except Exception as ex: print(ex) def compile_pj(): compileall.compile_dir(dist_dir, legacy=True) def remove_file(dir, postfix): """刪除指定目錄下指定后綴的文件""" if os.path.isdir(dir): for file in os.listdir(dir): remove_file(dir + '/' + file, postfix) else: if os.path.splitext(dir)[1] == postfix: os.remove(dir) def remove_dir(del_dir, filename="__pycache__"): """刪除__pycache__目錄""" if os.path.isdir(del_dir): for file in os.listdir(del_dir): if file == filename: shutil.rmtree(del_dir + '/' + file, True) remove_dir(del_dir + '/' + file) def main(): # 根目錄要拷貝的文件 copyfile = [ "main.py" ] # 根目錄要拷貝的目錄 copytree = [ "test1", "test2" ] mk_dist(copyfile=copyfile, copytree=copytree) compile_pj() remove_file(dist_dir, ".py") remove_dir(dist_dir, filename="__pycache__") if __name__ == "__main__": main()

 


免責聲明!

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



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