在Python开发中,将Python脚本打包成exe文件是常见需求。PyInstaller不仅能实现这一点,还能让我们自定义exe的版本信息。下面,让我们一步步来看如何实现。
创建版本信息文件
首先,我们需要一个file_version_info.txt
文件来存储版本信息。这个文件可以通过PyInstaller的pyi-grab_version.exe
程序获取。例如,如果你是通过PyCharm安装的PyInstaller,那么路径可能是:D:\PythonProject\Python38\venv\Scripts\pyi-grab_version.exe
。
运行下面的命令获取一个exe文件的版本信息,以获取WPS office的版本信息为例:
D:\PythonProject\Python38\venv\Scripts\pyi-grab_version.exe "C:\Users\liujialu\AppData\Local\Kingsoft\WPS Office\ksolaunch.exe"
这会在C:\Windows\System32
路径下生成file_version_info.txt
文件。你可以根据需求修改这个文件的内容。
打包exe并包含版本信息
将修改后的file_version_info.txt
放入欲打包的py文件相同目录下。
在PyCharm中,我们可以添加PyInstaller扩展工具来方便地打包exe文件。具体步骤如下:
-
在PyCharm中,点击菜单栏的
File
->Settings
->Tools
->External Tools
,点击右侧的加号按钮添加新的工具。 -
填写以下信息:
- Name:pyinstaller38
- Group:External Tools
- Program:D:\PythonProject\Python38\venv\Scripts\pyinstaller.exe
- Arguments:--noconsole --onefile --version-file version_info.txt $FileName$
- Working directory:$FileDir$
- 点击
OK
按钮保存设置。
现在,你可以在PyCharm的工程树中选中你想要打包的py文件,右键选择External Tool
-> pyinstaller38
进行打包。等待几分钟,你就可以在dist
文件夹中找到包含版本信息的exe文件了。
附录:
这是我获取的版本文件内容,可以新建一个txt复制后修改部分内容:
# UTF-8
#
# For more details about fixed file info 'ffi' see:
# http://msdn.microsoft.com/en-us/library/ms646997.aspx
VSVersionInfo(
ffi=FixedFileInfo(
# filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4)
# Set not needed items to zero 0.
filevers=(12, 1, 0, 15120),
prodvers=(12, 1, 0, 15120),
# Contains a bitmask that specifies the valid bits 'flags'r
mask=0x3f,
# Contains a bitmask that specifies the Boolean attributes of the file.
flags=0x0,
# The operating system for which this file was designed.
# 0x4 - NT and there is no need to change it.
OS=0x40004,
# The general type of file.
# 0x1 - the file is an application.
fileType=0x0,
# The function of the file.
# 0x0 - the function is not defined for this fileType
subtype=0x0,
# Creation date and time stamp.
date=(0, 0)
),
kids=[
StringFileInfo(
[
StringTable(
'000004b0',
[StringStruct('CompanyName', 'Zhuhai Kingsoft Office Software Co.,Ltd'),
StringStruct('FileDescription', 'WPS Office'),
StringStruct('FileVersion', '12,1,0,15120'),
StringStruct('InternalName', 'ksolaunch'),
StringStruct('LegalCopyright', 'Copyright©2023 Kingsoft Corporation. All rights reserved.'),
StringStruct('OriginalFilename', 'ksolaunch.exe'),
StringStruct('ProductName', 'WPS Office'),
StringStruct('ProductVersion', '12,1,0,15120'),
StringStruct('MIMEType', 'D')])
]),
VarFileInfo([VarStruct('Translation', [0, 1200])])
]
)