问题描述
今日用pyinstaller生成了一个exe文件,运行时一直出现ModuleNotFoundError: No module named 'models’错误。
(maskrcnn_yolov5) D:\project\cell_experts\dist\experts>experts.exe
Traceback (most recent call last):
File "experts.py", line 9, in <module>
File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module
File "cell_detection\cell_detector_batches.py", line 19, in <module>
ModuleNotFoundError: No module named 'models'
[138248] Failed to execute script 'experts' due to unhandled exception!
我的项目的目录结构如下所示:
|---cell_experts
--------|cell_detection
|---models
|---utils
--------|cell_analyser
cell_detector_batches.py的代码如下所示例:
# -*- coding: utf-8 -*-
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
import argparse
import sys
from pathlib import Path
import time, os
import numpy as np
import math
import cv2
import torch
import json
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from models.common import DetectMultiBackend
from utils.general import (LOGGER, check_img_size, check_requirements,
increment_path, non_max_suppression,nms_double, print_args, scale_coords, strip_optimizer, xyxy2xywh,cell_classifier,correct_axis)
from utils.torch_utils import select_device
使用的exe生成的命令:
pyinstaller -D experts.py
问题产生原因
PyInstaller 读取您编写的 Python 脚本。它分析您的代码以发现脚本执行所需的所有其他模块和库。然后它收集所有这些文件的副本——包括活动的 Python 解释器! – 并将它们与您的脚本放在一个文件夹中,或者可选地放在一个可执行文件中。
PyInstaller 会在您的脚本中查找所有import语句。它找到导入的模块并在其中查找导入语句,以此类推,直到它拥有您的脚本可能使用的模块的完整列表。
一些 Python 脚本以 PyInstaller 无法检测到的方式导入模块:例如,通过使用带有可变数据的 import() 函数、使用 importlib.import_module() 或在运行时操作 sys.path 值。如果你的脚本需要 PyInstaller 不知道的文件,你必须帮助它:
解决方法
pyinstaller --paths=D:\project\cell_experts\cell_detection --paths=D:\project\cell_experts\cell_analyser -D experts.py