安装PyInstaller
pip install pyinstaller
使用PyInstaller
打开 CMD 窗口,切换到 Python 脚本所在目录
pyinstaller --onefile your_script.py
CMD交互程序,添加 --console
选项
pyinstaller --onefile --console your_script.py
打包成管理员程序
创建一个名为 your_script.manifest
文件,和Python脚本同一目录
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
使用 PyInstaller 打包时包含 manifest 文件
pyinstaller --onefile --uac-admin your_script.py
# 明确指定manifest文件
pyinstaller --onefile --add-binary "your_script.manifest;." your_script.py
包含额外文件
pyinstaller --onefile --uac-admin --add-data "C:\Users\YourUsername\Desktop\your_image.png;." your_script.py
# 文件夹
pyinstaller --onefile --uac-admin --add-data "C:\Users\YourUsername\Desktop\images;images" your_script.py
使用打包后的文件
使用打包后的文件需要使用正确的路径来访问,打包后的程序运行环境与开发环境不同,需要使用sys._MEIPASS
来定位资源文件
import sys
import os
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# 使用方法
image_path = resource_path("your_image.png")
# 或者如果你把图片放在了 images 文件夹
# image_path = resource_path(os.path.join("images", "your_image.png"))
使用.spec文件打包
pyinstaller your_script.spec
添加额外数据文件
a = Analysis(
['your_script.py'],
pathex=[],
binaries=[],
datas=[('C:\\Users\\YourUsername\\Desktop\\your_image.png', '.'),
('C:\\Path\\To\\Your\\Folder', 'FolderName')],
# ...其他配置...
)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='YourAppName',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True, # 设置为 False 来创建一个无控制台窗口的应用
icon='path/to/your/icon.ico' # 添加应用图标
)
# 如果Python没有自动检测到某些必要的导入, 可以在Analysis对象中添加
a = Analysis(
['your_script.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=['package_name'],
# ...其他配置...
)