You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyInstaller设置onefile=True仍生成文件夹问题求助

解决PyInstaller onefile=True仍生成文件夹的问题

问题出在你的spec文件中同时保留了COLLECT代码块——当设置onefile=True时,COLLECT是多余的,它会强制生成包含多文件的文件夹结构,覆盖单文件打包的配置。

修复步骤:

  1. 修改main.spec文件:删除整个COLLECT代码块,修改后的spec文件如下:
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None

a = Analysis(
    ['main.py', 'ui_interface.py', 'utilities.py', 'data.py'],
    pathex=[],
    binaries=[],
    datas=[('MainMenu.ui', '.'), ('style.json', '.'), ('resources_rc.py', '.')],
    hiddenimports=[],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    [],
    exclude_binaries=True,
    name='D&PO UIB',
    debug=True,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    console=False,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    onefile=True,
)
  1. 重新执行打包命令:
pyinstaller main.spec
  1. 获取单文件可执行程序:打包完成后,单文件D&PO UIB.exe会生成在dist目录下。

额外注意事项

使用onefile模式时,程序运行会自动将依赖的资源文件(如MainMenu.ui、style.json)解压到系统临时目录。如果你的代码中直接使用相对路径读取这些文件,需要调整为从临时目录读取,可通过sys._MEIPASS获取临时路径:

import sys
import os

def get_resource_path(relative_path):
    try:
        # 打包后的临时路径
        base_path = sys._MEIPASS
    except Exception:
        # 开发环境下的路径
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

# 读取资源文件示例
ui_path = get_resource_path("MainMenu.ui")

内容的提问来源于stack exchange,提问作者Fares

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 06:53:10