HiDoz豆子 2024-03-30 12:51 采纳率: 0%
浏览 86

关于YOLOv8的GUI打包出现的问题

为什么我使用pyinstaller打包我的pyqt6项目,之后生成了exe文件,点击exe文件之后报错如下

Traceback (most recent call last):
  File "main.py", line 3, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
  File "mainWindow.py", line 17, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
  File "ultralytics\__init__.py", line 5, in <module>
    from ultralytics.data.explorer.explorer import Explorer
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
  File "ultralytics\data\__init__.py", line 3, in <module>
    from .base import BaseDataset
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
  File "ultralytics\data\base.py", line 17, in <module>
    from ultralytics.utils import DEFAULT_CFG, LOCAL_RANK, LOGGER, NUM_THREADS, TQDM
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
  File "ultralytics\utils\__init__.py", line 271, in <module>
    LOGGER = set_logging(LOGGING_NAME, verbose=VERBOSE)  # define globally (used in train.py, val.py, predict.py, etc.)
  File "ultralytics\utils\__init__.py", line 238, in set_logging
    if WINDOWS and sys.stdout.encoding != "utf-8":
AttributeError: 'NoneType' object has no attribute 'encoding'

当我打开ultralytics报错的片段“line238”

def set_logging(name=LOGGING_NAME, verbose=True):
    """Sets up logging for the given name with UTF-8 encoding support."""
    level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR  # rank in world for Multi-GPU trainings

    # Configure the console (stdout) encoding to UTF-8
    formatter = logging.Formatter("%(message)s")  # Default formatter
    if WINDOWS and sys.stdout.encoding != "utf-8":
        try:
            if hasattr(sys.stdout, "reconfigure"):
                sys.stdout.reconfigure(encoding="utf-8")
            elif hasattr(sys.stdout, "buffer"):
                import io

                sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
            else:
                sys.stdout.encoding = "utf-8"
        except Exception as e:
            print(f"Creating custom formatter for non UTF-8 environments due to {e}")

            class CustomFormatter(logging.Formatter):
                def format(self, record):
                    """Sets up logging with UTF-8 encoding and configurable verbosity."""
                    return emojis(super().format(record))

            formatter = CustomFormatter("%(message)s")  # Use CustomFormatter to eliminate UTF-8 output as last recourse

    # Create and configure the StreamHandler
    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(level)

    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(stream_handler)
    logger.propagate = False
    return logger


# Set logger
LOGGER = set_logging(LOGGING_NAME, verbose=VERBOSE)  # define globally (used in train.py, val.py, predict.py, etc.)
for logger in "sentry_sdk", "urllib3.connectionpool":
    logging.getLogger(logger).setLevel(logging.CRITICAL + 1)

当我打开ultralytics报错的片段“line273”

def yaml_load(file="data.yaml", append_filename=False):
    """
    Load YAML data from a file.

    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.

    Returns:
        (dict): YAML data and file name.
    """
    assert Path(file).suffix in (".yaml", ".yml"), f"Attempting to load non-YAML file {file} with yaml_load()"
    with open(file, errors="ignore", encoding="utf-8") as f:
        s = f.read()  # string

        # Remove special characters
        if not s.isprintable():
            s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+", "", s)

        # Add YAML filename to dict and return
        data = yaml.safe_load(s) or {}  # always return a dict (yaml.safe_load() may return None for empty files)
        if append_filename:
            data["yaml_file"] = str(file)
        return data

我发现都是跟编码问题有关encoding="utf-8",但是试了很多方法都没有效果

  • 写回答

2条回答 默认 最新

  • 关注

    中午好🌞🌞🌞
    本答案参考ChatGPT-3.5

    根据错误信息,问题似乎出在ultralytics库中的日志设置部分。具体地,出错的地方是在ultralytics.utils模块的set_logging函数的line 238处。

    错误信息中提到了一个'NoneType' object has no attribute 'encoding'的错误,这意味着sys.stdout对象为空,没有encoding属性。这通常是由于在GUI应用程序中使用pyinstaller打包时引起的。

    解决这个问题的一种方法是修改ultralytics.utils模块的set_logging函数,以确保在sys.stdout为空时不进行编码配置。

    解决方案:

    1. 打开ultralytics/utils/init.py文件。
    2. 找到set_logging函数,即第238行,将以下代码修改为:
    if WINDOWS and sys.stdout and sys.stdout.encoding and sys.stdout.encoding != "utf-8":
    
    1. 保存文件,并重新运行pyinstaller来生成exe文件。

    这样修改后,set_logging函数将首先检查sys.stdout是否存在,然后再检查其是否具有encoding属性。这样可以避免'NoneType' object has no attribute 'encoding'错误的出现。

    希望这个解决方案能够帮助你解决问题!如果仍然有其他问题,请随时提问。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 3月30日

悬赏问题

  • ¥20 求有缘人帮我把笛卡尔坐标系转换为经纬度 有偿
  • ¥15 vue2中使用计算属性
  • ¥50 远程桌面打开Mastercam、没有许可证、物理机打开正常
  • ¥15 ubuntu安装gdal后java读取tif文件报错
  • ¥15 请问lammps怎么做两种金属连接的原子浓度分布图
  • ¥15 求jacquard数据集
  • ¥15 w10部分软件不能联网
  • ¥15 关于安装hbase的问题(操作系统-windows)
  • ¥15 novnc连接pve虚拟机报错安全协议不支持262
  • ¥15 设备精度0.03给多少公差能达到CPK1.33