实例地址源码地址: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()