實例地址源碼地址: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()