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

Windows下PyInstaller打包后无法调用添加的esptool.exe问题

问题:PyInstaller打包后无法找到esptool.exe

直接运行Python脚本正常,但打包成exe后执行时报错:

'esptool' is not recognized as an internal or external command, operable program or batch file.

当前使用的PyInstaller命令

pyinstaller -F main.py -n "ProgramTest" -i resources/ico/icon.ico --add-binary "C:\\Users\\<my_user>\\AppData\\Local\\miniconda3\\envs\\this_env\\Scripts\\esptool.exe;."

注:esptool路径通过where.exe esptool获取,是唯一找到的实例

已尝试的无效方案

  • 使用等号连接参数:--add-binary="..."
  • 将目标路径设为lib:--add-binary="...;lib"

调用CMD的Python代码

import subprocess

def execute(cmd):
    popen = subprocess.Popen(
        cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True
    )
    for stdout_line in iter(popen.stdout.readline, ""):
        yield stdout_line
    popen.stdout.close()
    return popen.wait()

环境信息

  • 操作系统:Microsoft Windows 10 Pro
  • 版本:Windows 10.0.19045 Build 19045
  • miniconda:23.1.0
  • Python(虚拟环境):3.10.9
  • PyInstaller:5.8.0
  • esptool:3.1

解决方案

原因

打包后exe运行在临时目录,系统PATH不包含该目录,直接用esptool命令无法定位程序;且单文件模式下,PyInstaller会将添加的二进制文件解压到sys._MEIPASS指向的临时路径,需要动态获取该路径。

具体步骤

  1. 修改代码,动态获取esptool绝对路径
    在代码中加入路径判断逻辑,打包环境下用临时目录路径拼接esptool,非打包环境直接用系统命令:

    import subprocess
    import sys
    import os
    
    def get_esptool_path():
        if hasattr(sys, '_MEIPASS'):
            # 打包后,esptool.exe位于临时目录根目录(对应--add-binary的目标路径.)
            return os.path.join(sys._MEIPASS, 'esptool.exe')
        else:
            # 非打包环境,直接调用系统PATH中的esptool
            return 'esptool'
    
    def execute(cmd):
        # 将命令中的esptool替换为绝对路径
        esptool_path = get_esptool_path()
        cmd = cmd.replace('esptool', esptool_path)
        
        popen = subprocess.Popen(
            cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True
        )
        for stdout_line in iter(popen.stdout.readline, ""):
            yield stdout_line
        popen.stdout.close()
        return popen.wait()
    
  2. 保持原PyInstaller命令不变
    原命令中--add-binary的目标路径设为.,刚好对应临时目录根目录,无需修改:

    pyinstaller -F main.py -n "ProgramTest" -i resources/ico/icon.ico --add-binary "C:\\Users\\<my_user>\\AppData\\Local\\miniconda3\\envs\\this_env\\Scripts\\esptool.exe;."
    

注意事项

  • 如果你的命令是类似esptool --chip esp32 flash_id的格式,替换后会自动变成绝对路径调用,避免PATH依赖问题。
  • 单文件打包模式下,不要依赖系统PATH定位外部工具,必须用动态获取的绝对路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:31:00