博主首先参考了网上介绍的各种打包插件,只有三种被提及的比较多:
- pyinstaller
- py2exe
- cxfreeze
考虑到软件运行的多平台性,我首先使用了pyinstaller,可以在命令行通过pip install pyinstaller 安装该插件
遗憾的是安装过程很顺利,打包的时候却无法将脚本中导入的一些自定义本地模块相应的提取为依赖文件,例如自己写的utils工具类,导致打包出来的exe文件因缺少模块无法正确运行,闪退。谷歌百度无果,遂放弃。
失败后我用到了cxfreeze,因为相比较py2exe该插件始终持续更新:
pip安装之后在本地的 Python27 下 Scripts 文件夹中缺少 cxfreeze.bat 文件,虽然已经将 Scripts路径添加至系统环境变量 Path 中,依然无法找到 cxfreeze 命令
于是我在该文件夹下自行添加了一个 cxfreeze.bat 文件,用记事本编辑内容为:
@ echo off
C:\Python27\python.exe C:\Python27\Scripts\cxfreeze %*
继续运行 cxfeeze 命令,提示安装成功。(此处是我自己的安装路径)
接着输入命令进行打包:
cxfreeze D:\hello.py F:\666 dist
D盘下为打包文件,F盘下为存放exe的位置,如果希望打包成单个文件,可以选中所有文件右击自解压
问题在于打包好的exe文件夹大小过大,导入很多没有必要的依赖文件,需要手动删除,不是很方便
折腾了半天,最后还是选择了py2exe:
如果通过 pip 源安装报错,可能是因为python版本过低,可以选择网上搜索2.7的exe安装包
与之前不同的是,使用py2exe打包程序,需要准备一个setup.py文件放在需要打包的py文件相同目录下,内容为:
# coding=utf-8
from distutils.core import setup
import py2exe
options = {"py2exe": { "compressed": 1,
"optimize": 0,
"ascii": 0,
"bundle_files": 3,# 参数1不支持64位
'dist_dir': "F:/666",
#'build_dir':"D:/test/dir",
"includes":["sip"],
}
}
setup(options = options,
zipfile=None,
console = [{"script":r'D:\hello.py'}]
# console后为需要打包的文件的路径
)
以下为options对应的指令,根据情况设置:
optimize (-O) :optimization level, -O1 for “python -O”, -O2 for
“python -OO”, and -O0 (default) to disableexcludes (-e) : comma-separated list of modules to exclude
dll-excludes : comma-separated list of DLLs to exclude
ignores : comma-separated list of modules to ignore if they are not found
includes (-i) : comma-separated list of modules to include
packages (-p) : comma-separated list of packages to include
xref (-x) : create and show a module cross reference
bundle-files (-b) : bundle dlls in the zipfile or the exe. Valid levels are 1, 2, or 3 (default)
skip-archive : do not place Python bytecode files in an archive, put them directly in the file system
ascii (-a) : do not automatically include encodings and codecs
custom-boot-script : Python file that will be run when setting up the runtime environment
准备就绪后在控制台执行命令:
python setup.py py2exe
需要注意的是,如果python版本是2.7,运行时可能会报错,需要手动添加一个 MSVCR90.dll 文件至dist中或者与setup.py放一起,也可以直接在setup.py中设置:
from glob import glob
data_files = [(“Microsoft.VC90.CRT”, glob(r’C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT*.*’))]
setup(
data_files=data_files,
etc
)
详情请点击这里
但是这还不够,运行打包出来的exe时可能还是出现闪退现象,需要将 C:\Windows\system32 下的 python27.dll 手动拷贝进dist文件夹,此时再运行 exe 就不会有问题了,以上