You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何制作自动安装Tesseract等依赖的Python OCR程序EXE?

嘿,这个需求我之前帮团队处理过,给你几个落地性强的方案,一步步来就能解决:

方案1:用Inno Setup制作完整安装包(最推荐给团队使用)

这是Windows平台最常用的免费安装包制作工具,能把你的OCR程序+三个依赖工具打包成一个.exe安装文件,全程自动完成安装、环境变量配置,还能创建快捷方式。

  • 准备工作:
    • 下载好你的OCR程序.exe
    • 下载对应系统位数的三个依赖安装包:Tesseract的Windows静默安装包、ImageMagick官方安装包、Ghostscript官方安装包
  • 编写Inno Setup脚本(核心功能是自动静默安装依赖、添加环境变量、复制你的程序):
[Setup]
AppName=团队OCR工具
AppVersion=1.0
DefaultDirName={autopf}\团队OCR工具
OutputDir=.\安装包输出

[Files]
; 把三个依赖安装包和你的OCR程序放到脚本同目录
Source: "tesseract-ocr-w64-setup-v5.3.1.exe"; DestDir: "{tmp}"; Flags: deleteafterinstall
Source: "ImageMagick-7.1.1-Q16-HDRI-x64.exe"; DestDir: "{tmp}"; Flags: deleteafterinstall
Source: "gs9.56.1w64.exe"; DestDir: "{tmp}"; Flags: deleteafterinstall
Source: "my_ocr_app.exe"; DestDir: "{app}"

[Run]
; 静默安装三个依赖,参数对应各工具的静默安装命令
Filename: "{tmp}\tesseract-ocr-w64-setup-v5.3.1.exe"; Parameters: "/SILENT"; StatusMsg: "正在安装Tesseract..."
Filename: "{tmp}\ImageMagick-7.1.1-Q16-HDRI-x64.exe"; Parameters: "/silent"; StatusMsg: "正在安装ImageMagick..."
Filename: "{tmp}\gs9.56.1w64.exe"; Parameters: "/VERYSILENT"; StatusMsg: "正在安装Ghostscript..."
; 安装完成后可选启动你的OCR程序
Filename: "{app}\my_ocr_app.exe"; Description: "启动团队OCR工具"; Flags: nowait postinstall skipifsilent

[Registry]
; 把三个工具的安装路径添加到系统PATH(注意根据实际版本调整路径)
Root: "HKLM"; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: expandsz; ValueName: "PATH"; ValueData: "{olddata};C:\Program Files\Tesseract-OCR"; Flags: preservestringtype
Root: "HKLM"; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: expandsz; ValueName: "PATH"; ValueData: "{olddata};C:\Program Files\ImageMagick-7.1.1-Q16-HDRI"; Flags: preservestringtype
Root: "HKLM"; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; ValueType: expandsz; ValueName: "PATH"; ValueData: "{olddata};C:\Program Files\gs\gs9.56.1\bin"; Flags: preservestringtype
  • 最后用Inno Setup编译脚本,就能得到一个完整的安装.exe,团队成员双击就能完成所有配置。
方案2:PyInstaller配合启动脚本(纯Python层面解决)

如果你不想用外部安装包工具,可以写一个启动脚本,先检查并自动安装依赖,再启动你的OCR程序,最后把启动脚本和主程序一起打包成一个.exe。

  • 编写启动脚本bootstrapper.py
import os
import subprocess
import tempfile
import urllib.request
import ctypes
import winreg

def check_tool_exists(tool_name):
    try:
        subprocess.run([tool_name, '--version'], capture_output=True, text=True, check=True)
        print(f"✅ {tool_name}已安装")
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        print(f"❌ {tool_name}未找到,开始自动安装...")
        return False

def install_tesseract():
    installer_url = "https://github.com/UB-Mannheim/tesseract/releases/download/v5.3.1/tesseract-ocr-w64-setup-v5.3.1.20230401.exe"
    with tempfile.NamedTemporaryFile(delete=False, suffix='.exe') as tmp_file:
        urllib.request.urlretrieve(installer_url, tmp_file.name)
    subprocess.run([tmp_file.name, '/SILENT'], check=True)
    os.unlink(tmp_file.name)

def install_imagemagick():
    installer_url = "https://imagemagick.org/archive/binaries/ImageMagick-7.1.1-Q16-HDRI-x64.exe"
    with tempfile.NamedTemporaryFile(delete=False, suffix='.exe') as tmp_file:
        urllib.request.urlretrieve(installer_url, tmp_file.name)
    subprocess.run([tmp_file.name, '/silent'], check=True)
    os.unlink(tmp_file.name)

def install_ghostscript():
    installer_url = "https://github.com/ArtifexSoftware/ghostpdl-downloads/releases/download/gs9561/gs9561w64.exe"
    with tempfile.NamedTemporaryFile(delete=False, suffix='.exe') as tmp_file:
        urllib.request.urlretrieve(installer_url, tmp_file.name)
    subprocess.run([tmp_file.name, '/VERYSILENT'], check=True)
    os.unlink(tmp_file.name)

def add_to_path(path):
    current_path = os.environ.get('PATH', '')
    if path not in current_path:
        # 修改系统注册表PATH
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 0, winreg.KEY_SET_VALUE)
        existing_path = winreg.QueryValueEx(key, 'PATH')[0]
        new_path = existing_path + ';' + path
        winreg.SetValueEx(key, 'PATH', 0, winreg.REG_EXPAND_SZ, new_path)
        winreg.CloseKey(key)
        # 通知系统立即更新环境变量(无需重启)
        ctypes.windll.user32.SendMessageW(0xFFFF, 0x1A, 0, 'Environment')
        print(f"📌 已将{path}添加到系统PATH")

def main():
    # 检查并安装所有依赖
    if not check_tool_exists('tesseract'):
        install_tesseract()
        add_to_path(r"C:\Program Files\Tesseract-OCR")
    
    if not check_tool_exists('magick'):
        install_imagemagick()
        add_to_path(r"C:\Program Files\ImageMagick-7.1.1-Q16-HDRI")
    
    if not check_tool_exists('gswin64c'):
        install_ghostscript()
        add_to_path(r"C:\Program Files\gs\gs9.56.1\bin")
    
    # 启动你的OCR主程序
    print("🚀 启动团队OCR工具...")
    subprocess.run([os.path.join(os.path.dirname(__file__), 'my_ocr_app.exe')], check=True)

if __name__ == "__main__":
    main()
  • 打包命令:pyinstaller --onefile --add-data "my_ocr_app.exe;." bootstrapper.py
  • 注意:下载链接要选稳定版本,避免后续失效;如果用户自定义安装路径,你可以加个逻辑搜索注册表找实际路径,不要硬编码。
方案3:用Chocolatey自动安装(最省心的依赖管理)

如果团队允许使用Chocolatey(Windows包管理器),这个方法不用自己找安装包,一键搞定所有依赖:

  • 启动脚本里先安装Chocolatey(如果没有的话),再用它安装三个工具:
def install_chocolatey():
    try:
        subprocess.run(['choco', '--version'], check=True)
    except FileNotFoundError:
        print("安装Chocolatey包管理器...")
        subprocess.run(
            ['powershell', '-Command', 'Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString(\'https://community.chocolatey.org/install.ps1\'))'],
            check=True
        )

def main():
    install_chocolatey()
    print("安装所有依赖工具...")
    subprocess.run(['choco', 'install', 'tesseract', 'imagemagick', 'ghostscript', '-y'], check=True)
    print("启动OCR工具...")
    subprocess.run(['my_ocr_app.exe'], check=True)
  • 优点:不用维护安装包链接,自动下载最新稳定版,环境变量自动配置;缺点:需要联网,部分公司网络可能限制PowerShell脚本下载。
额外小贴士
  • 一定要在干净的Windows 10虚拟机里测试,确保全程无交互弹窗,所有步骤自动完成。
  • 如果Tesseract需要特定语言训练数据,可以提前下载好放到程序目录,设置TESSDATA_PREFIX环境变量指向该目录,不用用户手动下载。

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

火山引擎 最新活动