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

PyInstaller打包EXE后路径错误问题求助

PyInstaller打包EXE后路径错误的解决办法

问题出在os.path.abspath(__file__)的路径获取逻辑上:当用PyInstaller -F参数打包成单文件EXE后,程序运行时会被临时解压到系统临时目录,此时__file__指向的是临时目录里的脚本文件(比如你遇到的C:\Users\User\AppData\Local\Temp\_MEI36682\base_library.zip\os.pyc这类路径),完全不是你实际运行EXE的目录,导致拼接出来的文件路径根本找不到下载好的zip。

修复后的代码

import wget
import zipfile
import os
import sys

def get_root_path():
    # 判断当前是否为PyInstaller打包后的可执行程序
    if getattr(sys, 'frozen', False):
        # 打包状态:返回EXE文件所在的目录
        return os.path.dirname(os.path.abspath(sys.executable))
    else:
        # 脚本状态:返回当前脚本所在的目录
        return os.path.dirname(os.path.abspath(__file__))

url = 'https://example.com/file.zip'
current_path = get_root_path()
# 指定文件下载到程序根目录
target_file = os.path.join(current_path, 'file.zip')
wget.download(url, out=target_file)

try:
    with zipfile.ZipFile(target_file, 'r') as zip_ref:
        zip_ref.extractall(current_path)
except Exception as e:
    print(e)

os.startfile(os.path.join(current_path, 'main.exe'))

关键修改点

  • 新增get_root_path函数:通过sys.frozen属性区分脚本运行和打包后的状态,确保拿到的是实际程序所在目录,而非临时解压目录
  • 用os.path.join拼接路径:自动适配Windows的\\和其他系统的/,避免手动写分隔符引发的错误
  • 直接指定wget的下载路径:让文件直接下载到目标目录,无需后续再拼接路径,减少出错概率

内容的提问来源于stack exchange,提问作者Chall-T

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:45:30