废话不多说,有时候需要将一些参数打包到exe中,不希望用户看到。
1.需要在cmd窗口下安装打包库,pip install pyinstaller
2.如果只需要打包DLL到exe中,只需要再pycahrm终端中输入指令
pyinstaller -F -w --onefile --add-data "D:\\Works\\GC_CAN\\ECanVci64.dll;." GC_CAN_main.py,其中--onefile --add-data "D:\\Works\\GC_CAN\\ECanVci64.dll;."是打包DLL关键指令。--onefile参数表示将所有文件打包成一个exe文件,--add-data参数用于指定需要打包的dll文件。
那么要增加2个文件怎么办呢,使用以下命令
pyinstaller -F -w --onefile --add-data "D:\\Works\\Python-Project(2020.03.11.09)\\GC_CAN\\ECanVci64.dll;." --add-data "D:\\Works\\Python-Project(2020.03.11.09)\\GC_CAN\\test.INI;." GC_CAN_main.py
还需要在py程序中修改相对路径,使用以下方法
base_dir = os.path.abspath(os.path.dirname(__file__)) # 很重要的相对路径设置
self.adressB = os.path.join(base_dir, 'test.ini')
self.open_ini(self.adressB) # 自定义的对路径文件进行访问
3.使用spec打包
# -*- mode: python ; coding: utf-8 -*-
a = Analysis(
['GC_CAN_main.py'],
pathex=[],
binaries=[],
datas=[('D:\\\\Works\\\\Python-Project(2020.03.11.09)\\\\GC_CAN\\\\ECanVci64.dll', '.'), ('D:\\\\Works\\\\Python-Project(2020.03.11.09)\\\\GC_CAN\\\\test.INI', '.')],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
noarchive=False,
optimize=0,
)
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
name='GC_CAN_main',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
直接在终端使用pyinstaller xx.spec打包程序就行,但是需要删除dist和build两个文件,再单独使用pyinstaller xx.spec打包生成exe。datas=[('D:\\\\Works\\\\Python-Project(2020.03.11.09)\\\\GC_CAN\\\\ECanVci64.dll', '.'), ('D:\\\\Works\\\\Python-Project(2020.03.11.09)\\\\GC_CAN\\\\test.INI', '.')],主要修改这个位置数据
4.使用工具进行打包,先安装pip install auto-py-to-exe,这个工具是相当的好用。我现在基本都是在用这个软件进行打包,可以打包dll,图片,ini,txt各种文件,但是最重要的事需要在程序里面调用各种文件时候,这样打包盒运行时候才会从程序运行路径下打开文件
base_dir = os.path.abspath(os.path.dirname(__file__)) # 使用相对路径的基准目录
self.adressB = os.path.join(base_dir, 'test.ini')
然后cmd运行pip install auto-py-to-exe,出现以前界面
选中添加附件,将资源一起打包到exe中