PyInstaller: «ModuleNotFoundError: нет модуля с именем 'typing_extensions'» Ошибка в автономном исполняемом файлеPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 PyInstaller: «ModuleNotFoundError: нет модуля с именем 'typing_extensions'» Ошибка в автономном исполняемом файле

Сообщение Anonymous »

Описание:
Я пытаюсь упаковать приложение Python в автономный исполняемый файл с помощью PyInstaller. Приложение использует несколько библиотек, включая PyTorch. Несмотря на включение typing_extensions в скрытый импорт, я все равно сталкиваюсь с ошибкой ModuleNotFoundError для typing_extensions при запуске исполняемого файла в клиентской системе.
Среда:
ОС: Windows 11
Python Версия: 3.12.3
Версия PyInstaller: 6.6.0
Виртуальная среда: Да (с использованием .venv)
Структура каталогов:
project-root/
├── GUI4.py
├──ook-torch.py
├── gui4.spec
└── .venv/
└── Lib /
└── site-packages/
└── (все установленные пакеты, включая torch и typing_extensions)
Проблема:
Когда я запускаю сгенерированный исполняемый файл в клиентской системе, я получаю следующую ошибку:
Ошибка: Traceback (последний вызов):

Код: Выделить всё

type here
Файл "C:\Path\to\Executable\NewExecutableName\NewExecutableName_internal\detect.py", строка 38, в
импорте факела
Файл "C:\ Путь\to\Executable\NewExecutableName\NewExecutableName_internal\torch_init_.py", строка 1403, в
из сохранения импорта .serialization, загрузите
файл "C:\Path\ to\Executable\NewExecutableName\NewExecutableName_internal\torch\serialization.py", строка 18, в
из typing_extensions import TypeAlias ​​# Python 3.10+
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
ModuleNotFoundError: нет модуля с именем 'typing_extensions'
Файл спецификации:
Вот мой файл gui4.spec:

Код: Выделить всё

# -*- mode: python ;  coding: utf-8 -*-

block_cipher = None

a = Analysis(
['GUI4.py'],
pathex=['.'],
binaries=[],
datas=[
('weights/best.pt', 'weights'),
('detect.py', '.'),
('models', 'models'),
('utils', 'utils'),
('data', 'data'),
('export.py', '.'),
('requirements.txt', '.'),
],
hiddenimports=[
'models.common',
'utils.general',
'utils.plots',
'export',
'typing_extensions',
'torch',
'torch.utils.tensorboard',
],
hookspath=['.', 'Path\\to\\your\\project\\.venv\\Lib\\site-packages'],
runtime_hooks=[],
excludes=[
'torch.distributed._shard.checkpoint._dedup_tensors',
'torch.distributed._shard.checkpoint._fsspec_filesystem',
'torch.distributed._shard.checkpoint._nested_dict',
'torch.distributed._shard.checkpoint._sharded_tensor_utils',
'torch.distributed._shard.checkpoint._state_dict_utils',
'torch.distributed._shard.checkpoint._traverse',
'torch.distributed._shard.checkpoint.api',
'torch.distributed._shard.checkpoint.default_planner',
'torch.distributed._shard.checkpoint.filesystem',
'torch.distributed._shard.checkpoint.metadata',
'torch.distributed._shard.checkpoint.optimizer',
'torch.distributed._shard.checkpoint.planner',
'torch.distributed._shard.checkpoint.planner_helpers',
'torch.distributed._shard.checkpoint.resharding',
'torch.distributed._shard.checkpoint.state_dict',
'torch.distributed._shard.checkpoint.state_dict_loader',
'torch.distributed._shard.checkpoint.state_dict_saver',
'torch.distributed._shard.checkpoint.stateful',
'torch.distributed._shard.checkpoint.storage',
'torch.distributed._shard.checkpoint.utils',
'torch.distributed._sharded_tensor._ops',
'torch.distributed._sharded_tensor._ops._common',
'torch.distributed._sharded_tensor._ops.binary_cmp',
'torch.distributed._sharded_tensor._ops.init',
'torch.distributed._sharded_tensor._ops.misc_ops',
'torch.distributed._sharded_tensor._ops.tensor_ops',
'torch.distributed._sharded_tensor.api',
'torch.distributed._sharded_tensor.logger',
'torch.distributed._sharded_tensor.logging_handlers',
'torch.distributed._sharded_tensor.metadata',
'torch.distributed._sharded_tensor.reshard',
'torch.distributed._sharded_tensor.shard',
'torch.distributed._sharded_tensor.utils',
'torch.distributed._sharding_spec._internals',
'torch.distributed._sharding_spec.api',
'torch.distributed._sharding_spec.chunk_sharding_spec',
'torch.distributed._sharding_spec.chunk_sharding_spec_ops',
'torch.distributed._sharding_spec.chunk_sharding_spec_ops._common',
'torch.distributed._sharding_spec.chunk_sharding_spec_ops.embedding',
'torch.distributed._sharding_spec.chunk_sharding_spec_ops.embedding_bag',
],
noarchive=False,
optimize=0,
cipher=block_cipher,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name='GUI4',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)

coll = COLLECT(
exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='GUI4',
)
Пользовательский перехват:
Я также создал собственный перехватчик для PyTorch, чтобы обеспечить включение всех зависимостей:
hook-torch.py:

Код: Выделить всё

from PyInstaller.utils.hooks import collect_all

datas, binaries, hiddenimports = collect_all('torch')

typing_extensions_datas, typing_extensions_binaries, typing_extensions_hiddenimports = collect_all('typing_extensions')

datas += typing_extensions_datas
binaries += typing_extensions_binaries
hiddenimports += typing_extensions_hiddenimports

binaries = binaries
datas = datas
hiddenimports = hiddenimports
Предпринятые шаги:
Установлены все зависимости в виртуальной среде.
Создан файл спецификации, включены необходимые файлы данных и скрытый импорт.
Добавлен сайт. -packages к пути перехвата в файле спецификации.
Создан специальный перехватчик, обеспечивающий включение PyTorch и typing_extensions.
Запуск PyInstaller с файлом спецификации для создания исполняемого файла.
Проблема:
Несмотря на эти усилия, исполняемый файл по-прежнему завершается с ошибкой ModuleNotFoundError для typing_extensions в клиентской системе.
Запрос:
Мне нужна помощь в определении, почему typing_extensions не включается в автономную версию. исполняемый файл и способы решения этой проблемы.
Будем очень признательны за любые идеи и предложения!

Подробнее здесь: https://stackoverflow.com/questions/785 ... s-error-in
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»