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

使用PyInstaller打包项目后,其他PC运行exe文件报错求助

解决PyInstaller打包exe后其他电脑无法打开SQLite数据库的问题

报错信息

Traceback (most recent call last):
File "main.py", line 5, in
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "PyInstaller/loader/pyimod02_importers.py", line 391, in exec_module
File "Create_table/create_table_PT.py", line 3, in
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "PyInstaller/loader/pyimod02_importers.py", line 391, in exec_module
File "db_connection.py", line 12, in
sqlite3.OperationalError: unable to open database file
[41403] Failed to execute script 'main' due to unhandled exception!

核心原因

本地运行时数据库路径有效,但打包后其他电脑上要么找不到数据库文件,要么没有读写权限,或者路径写法错误。

解决方案

1. 修正数据库路径的代码写法

绝对路径(比如C:\myproject\db.sqlite)只能在你的电脑上生效,必须改成相对当前exe的动态路径。在db_connection.py里修改连接代码:

import os
import sys
import sqlite3

def get_database_path():
    # 判断是否处于PyInstaller打包后的运行环境
    if getattr(sys, 'frozen', False):
        # 打包后exe所在的目录
        exe_dir = os.path.dirname(sys.executable)
    else:
        # 开发模式下当前脚本的目录
        exe_dir = os.path.dirname(os.path.abspath(__file__))
    # 拼接数据库文件名
    return os.path.join(exe_dir, "你的数据库文件名.sqlite")

# 连接数据库
conn = sqlite3.connect(get_database_path())

2. 确保数据库文件被打包进exe

如果你的数据库是预先创建好的文件,需要告诉PyInstaller把它一起打包:

  • 命令行方式(Windows):
    pyinstaller --add-data "你的数据库文件名.sqlite;." main.py
    
    (Linux/macOS把分号改成冒号:--add-data "你的数据库文件名.sqlite:.")
  • 或者修改spec文件:
    在Analysis部分的datas参数里添加数据库文件:
    a = Analysis(
        ['main.py'],
        datas=[('你的数据库文件名.sqlite', '.')],
        # 其他参数...
    )
    
    然后执行pyinstaller main.spec打包。

3. 避免无权限的运行目录

不要把exe放在Program Files这类需要管理员权限的目录,建议用户把exe放在桌面、文档或自定义文件夹里运行,确保有读写权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:43:11