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

PyInstaller打包exe运行时_build_ssl_context报文件不存在错误求助

PyInstaller打包exe后textmagic请求报FileNotFoundError解决方法

问题表现

Python脚本在本地直接运行正常,使用PyInstaller打包为exe后,调用textmagic库发起HTTP请求时抛出如下错误:

File "main.py", line 88, in <module>
  File "main.py", line 20, in send_generics
  File "textmagic/rest/models/messages.py", line 91, in create
  File "textmagic/rest/models/base.py", line 214, in create_instance
  File "textmagic/rest/models/base.py", line 156, in request
  File "textmagic/rest/models/base.py", line 121, in make_tm_request
  File "textmagic/rest/models/base.py", line 86, in make_request
  File "httplib2/__init__.py", line 1558, in request
  File "httplib2/__init__.py", line 1077, in __init__
  File "httplib2/__init__.py", line 172, in _build_ssl_context
FileNotFoundError: [Errno 2] No such file or directory

问题原因

报错本质是PyInstaller打包时没有自动收集httplib2库依赖的CA根证书文件cacerts.txt,且之前尝试的打包命令中--add-data参数的目标路径配置错误,误将证书文件放到了textmagic的目录下,导致httplib2初始化SSL上下文时找不到证书文件。

解决步骤

  • 第一步:确认本机httplib2证书文件的绝对路径,执行如下命令获取:
python -c "from httplib2 import certs; print(certs.where())"

执行后会输出类似/usr/local/lib/python3.10/site-packages/httplib2/cacerts.txt(Linux/macOS)或C:\Users\xxx\AppData\Roaming\Python\Python310\site-packages\httplib2\cacerts.txt(Windows)的路径。

  • 第二步:修正PyInstaller打包命令的--add-data参数,将证书文件的目标路径指定为httplib2(而非之前的textmagic子目录),不同系统的命令格式有区别:
    • Linux/macOS系统(路径分隔用冒号):
    pyinstaller --add-data "$(python -c 'from httplib2 import certs; print(certs.where())'):httplib2" main.py
    
    • Windows系统(cmd环境,路径分隔用分号):
      先将第一步获取到的证书绝对路径替换到如下命令中:
    pyinstaller --add-data "C:\你的实际证书路径\cacerts.txt;httplib2" main.py
    
  • 第三步(可选,适配稳定性更高):在代码最开头(导入textmagic、httplib2相关模块之前)添加如下路径适配代码,避免运行时路径解析错误:
import sys
import os
from httplib2 import certs

# 适配PyInstaller打包后的运行环境
if getattr(sys, 'frozen', False):
    # 打包后程序会将依赖文件解压到_MEIPASS临时目录下
    certs.where = lambda: os.path.join(sys._MEIPASS, 'httplib2', 'cacerts.txt')

重新打包后即可正常发起HTTPS请求,不会再抛出文件找不到的错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 01:06:25