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

使用PyInstaller打包YOLOv8人体检测Python程序为EXE时遇错误求助

解决YOLOv8程序PyInstaller打包EXE时的AttributeError问题

问题根源

PyInstaller打包后,Windows环境下若程序以无控制台模式(--windowed/--noconsole)运行,或控制台输出被重定向时,sys.stdout会被置为None,而ultralytics工具库的set_logging函数直接访问sys.stdout.encoding,触发'NoneType' object has no attribute 'encoding'错误。

解决方案

方案1:主脚本添加猴子补丁(无需修改库源码)

在你的Python主脚本最开头加入以下代码,提前初始化sys.stdout和sys.stderr:

import sys
import os

# 处理stdout/stderr为None的情况,重定向到空设备
if sys.stdout is None:
    sys.stdout = open(os.devnull, 'w', encoding='utf-8')
if sys.stderr is None:
    sys.stderr = open(os.devnull, 'w', encoding='utf-8')

# 之后再导入ultralytics相关模块
from ultralytics import YOLO
# 你的业务代码...

方案2:修改ultralytics库源码

找到Python环境中ultralytics/utils/__init__.py文件,定位set_logging函数内的代码行:

if WINDOWS and sys.stdout.encoding != 'utf-8':

修改为:

if WINDOWS and sys.stdout is not None and sys.stdout.encoding != 'utf-8':

保存后重新执行打包命令即可。

方案3:打包时保留控制台(仅适用于非GUI程序)

若程序无需隐藏控制台,打包时使用--console参数(默认启用,若之前用了--windowed则移除):

pyinstaller --onefile your_script.py

额外注意事项

  • 确保YOLOv8权重文件(如yolov8n.pt)被正确打包,可通过--add-data参数指定:
    pyinstaller --onefile --add-data "yolov8n.pt;." your_script.py
    
    (Windows用;分隔路径,Linux/macOS用:)
  • 若使用虚拟环境,打包前需激活对应环境,避免依赖缺失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 11:43:15