PyInstaller打包EXE无法运行,python3 main.py可正常执行的问题求助
解决方案
1. 修复代码中的路径问题
PyInstaller打包后,程序会运行在临时目录,原有的相对路径dist无法正确指向React构建产物。需要修改代码,适配打包后的路径逻辑:
修改后的main.py代码:
import webview from flask import Flask, send_from_directory import sys import os def get_resource_path(relative_path): # 适配PyInstaller打包后的资源路径 if hasattr(sys, '_MEIPASS'): return os.path.join(sys._MEIPASS, relative_path) return os.path.join(os.path.abspath("."), relative_path) # Initialize Flask application,使用动态获取的dist路径 app = Flask(__name__, static_folder=get_resource_path("dist"), static_url_path="") # Serve the React frontend @app.route("/") def index(): return send_from_directory(get_resource_path("dist"), "index.html") # Example API endpoint @app.route("/api/data") def get_data(): return {"message": "Hello from Python API"} def start_flask_app(): app.run(host="localhost", port=5001) def start_pywebview(): webview.create_window("My App", "http://localhost:5001", width=800, height=600) webview.start() if __name__ == "__main__": import threading flask_thread = threading.Thread(target=start_flask_app) flask_thread.start() start_pywebview()
2. 告诉PyInstaller打包dist文件夹
打包时必须将React的dist目录包含到exe中,否则程序运行时找不到静态文件。
方式一:直接用命令行打包
在PowerShell/CMD中执行:
pyinstaller --onefile --add-data "dist;dist" main.py
注意:Windows系统用分号
;分隔源路径和目标路径,Linux/macOS用冒号:
方式二:使用spec文件打包(更灵活)
- 生成默认spec文件:
pyi-makespec main.py
- 打开生成的
main.spec,找到datas参数,修改为:
datas = [('dist', 'dist')],
- 执行打包:
pyinstaller main.spec
3. 测试运行
打包完成后,进入PyInstaller生成的dist目录,运行main.exe即可正常加载React前端。
内容的提问来源于stack exchange,提问作者Seco01
相关产品推荐
相关产品推荐

