#python #pyinstaller
#python #pyinstaller
Вопрос:
Я пытаюсь поместить простой сервер flask в исполняемый файл с помощью pyinstaller -F server.py
command
При запуске exe-файла я получаю следующую ошибку:
Traceback (most recent call last):
File "server.py", line 4, in <module>
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "c:userspcappdatalocalprogramspythonpython36libsite-packagesPyInstallerloaderpyimod03_importers.py", line 493, in exec_module
exec(bytecode, module.__dict__)
File "transform.py", line 17, in <module>
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "c:userspcappdatalocalprogramspythonpython36libsite-packagesPyInstallerloaderpyimod03_importers.py", line 493, in exec_module
exec(bytecode, module.__dict__)
File "convert.py", line 12, in <module>
File "pymorphy2analyzer.py", line 200, in __init__
File "pymorphy2analyzer.py", line 280, in choose_dictionary_path
File "pymorphy2analyzer.py", line 144, in lang_dict_path
ValueError: Can't find a dictionary for language 'ru'. Installed languages: []. Try installing pymorphy2-dicts-ru package.
[18156] Failed to execute script server
Уже пытался pip install pymorphy2-dicts-ru
, это не помогло
Ниже приведены журналы pyinstaller -F server.py
96 INFO: PyInstaller: 4.1
97 INFO: Python: 3.6.8
97 INFO: Platform: Windows-10-10.0.19041-SP0
103 INFO: wrote C:UserspcDesktophackcodenlp-serverserver.spec
118 INFO: UPX is not available.
122 INFO: Extending PYTHONPATH with paths
['C:\Users\pc\Desktop\hack\code\nlp-server',
'C:\Users\pc\Desktop\hack\code\nlp-server']
139 INFO: checking Analysis
140 INFO: Building Analysis because Analysis-00.toc is non existent
140 INFO: Initializing module dependency graph...
145 INFO: Caching module graph hooks...
169 INFO: Analyzing base_library.zip ...
3178 INFO: Caching module dependency graph...
3265 INFO: running Analysis Analysis-00.toc
3268 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
required by c:userspcappdatalocalprogramspythonpython36python.exe
3440 INFO: Analyzing C:UserspcDesktophackcodenlp-serverserver.py
4658 INFO: Processing pre-find module path hook distutils from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks\pre_find_module_path\hook-distutils.py'.
4659 INFO: distutils: retargeting to non-venv dir 'c:\users\pc\appdata\local\programs\python\python36\lib'
7000 INFO: Processing pre-safe import module hook setuptools.extern.six.moves from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks\pre_safe_import_module\hook-setuptools.extern.six.m
oves.py'.
7477 INFO: Processing pre-find module path hook site from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks\pre_find_module_path\hook-site.py'.
7478 INFO: site: retargeting to fake-dir 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\fake-modules'
10016 INFO: Processing module hooks...
10017 INFO: Loading module hook 'hook-jinja2.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks'...
10031 INFO: Loading module hook 'hook-difflib.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10034 INFO: Excluding import of doctest from module difflib
10034 INFO: Loading module hook 'hook-distutils.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10035 INFO: Loading module hook 'hook-distutils.util.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10038 INFO: Excluding import of lib2to3.refactor from module distutils.util
10038 INFO: Loading module hook 'hook-encodings.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10146 INFO: Loading module hook 'hook-heapq.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10148 INFO: Excluding import of doctest from module heapq
10149 INFO: Loading module hook 'hook-lib2to3.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10247 INFO: Loading module hook 'hook-multiprocessing.util.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10249 INFO: Import to be excluded not found: 'test'
10249 INFO: Loading module hook 'hook-numpy.core.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10827 INFO: Loading module hook 'hook-numpy.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10830 INFO: Loading module hook 'hook-numpy._pytesttester.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10832 INFO: Excluding import of pytest from module numpy._pytesttester
10833 INFO: Loading module hook 'hook-pickle.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
10835 INFO: Excluding import of argparse from module pickle
10835 INFO: Loading module hook 'hook-pkg_resources.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
11162 INFO: Processing pre-safe import module hook win32com from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\_pyinstaller_hooks_contrib\hooks\pre_safe_import_module\hook-win32com.py'.
Traceback (most recent call last):
File "<string>", line 2, in <module>
ModuleNotFoundError: No module named 'win32com'
11219 INFO: Processing pre-safe import module hook win32com from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\_pyinstaller_hooks_contrib\hooks\pre_safe_import_module\hook-win32com.py'.
Traceback (most recent call last):
File "<string>", line 2, in <module>
ModuleNotFoundError: No module named 'win32com'
11462 WARNING: Hidden import "pkg_resources.py2_warn" not found!
11464 WARNING: Hidden import "pkg_resources.markers" not found!
11465 INFO: Excluding import of __main__ from module pkg_resources
11466 INFO: Loading module hook 'hook-setuptools.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
12062 INFO: Excluding import of setuptools.py27compat from module setuptools.command.easy_install
12062 INFO: Excluding import of setuptools.py27compat from module setuptools.package_index
12065 INFO: Excluding import of setuptools.py33compat from module setuptools.depends
12065 INFO: Excluding import of setuptools.py33compat from module setuptools.package_index
12066 INFO: Loading module hook 'hook-sysconfig.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
12067 INFO: Loading module hook 'hook-xml.etree.cElementTree.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
12068 INFO: Loading module hook 'hook-xml.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
12121 INFO: Loading module hook 'hook-setuptools.msvc.py' from 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks'...
12123 INFO: Excluding import of numpy from module setuptools.msvc
12199 INFO: Looking for ctypes DLLs
12231 INFO: Analyzing run-time hooks ...
12237 INFO: Including run-time hook 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgres.py'
12238 INFO: Including run-time hook 'c:\users\pc\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_multiprocessing.py'
12250 INFO: Looking for dynamic libraries
13139 INFO: Looking for eggs
13139 INFO: Using Python library c:userspcappdatalocalprogramspythonpython36python36.dll
13139 INFO: Found binding redirects:
[]
13150 INFO: Warnings written to C:UserspcDesktophackcodenlp-serverbuildserverwarn-server.txt
13296 INFO: Graph cross-reference written to C:UserspcDesktophackcodenlp-serverbuildserverxref-server.html
13324 INFO: checking PYZ
13325 INFO: Building PYZ because PYZ-00.toc is non existent
13326 INFO: Building PYZ (ZlibArchive) C:UserspcDesktophackcodenlp-serverbuildserverPYZ-00.pyz
14479 INFO: Building PYZ (ZlibArchive) C:UserspcDesktophackcodenlp-serverbuildserverPYZ-00.pyz completed successfully.
14505 INFO: checking PKG
14505 INFO: Building PKG because PKG-00.toc is non existent
14505 INFO: Building PKG (CArchive) PKG-00.pkg
20039 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
20043 INFO: Bootloader c:userspcappdatalocalprogramspythonpython36libsite-packagesPyInstallerbootloaderWindows-64bitrun.exe
20043 INFO: checking EXE
20043 INFO: Building EXE because EXE-00.toc is non existent
20043 INFO: Building EXE from EXE-00.toc
20044 INFO: Appending archive to EXE C:UserspcDesktophackcodenlp-serverdistserver.exe
20060 INFO: Building EXE from EXE-00.toc completed successfully.
код server.py
from flask import Flask, request, jsonify
from transform import transform_text
server = Flask(__name__);
@server.route('/send', methods=['POST'])
def send():
print("POST /send request")
# obtaining passed args
fname = request.json['fname']
text = request.json['text']
# updating the text
text = f"{transform_text(text, 'Masc', fname)}"
# sending back updated text
return jsonify({'text': text})
if __name__ == '__main__':
server.run(host='0.0.0.0', port='8080', debug=True)
tranform_text()
функция использует pymorphy для изменения предложений с формы от 1-го лица («Я играю») на форму от 3-го лица («Он / она играет»)
Итак, есть ли какой-нибудь способ заставить исполняемый файл работать?
Ответ №1:
Это проблема пакета;pymorphy2_dicts_ru;. Файлы из каталога данных не копируются в пакет.
Чтобы решить проблему, вам необходимо выполнить два шага:
- Добавьте каталог данных в файл спецификации pyinstaller:
... # pymorph data import pymorphy2_dicts_ru pymorph_data = pymorphy2_dicts_ru.get_path() a = Analysis(['main.py'], pathex=['.'], binaries=[], datas=[(pymorph_data, 'pymorphy2_dicts_ru/data')], hiddenimports=[], hookspath=[], ...
- Задайте путь к каталогу данных в коде перед импортом модуля pymorphy2 (в main.py например):
... if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): os.environ["PYMORPHY2_DICT_PATH"] = str(pathlib.Path(sys._MEIPASS).joinpath('pymorphy2_dicts_ru/data')) ...
Комментарии:
1. Это кажется грязным решением, но для меня оно отлично сработало. Если кто-нибудь придумает более простой подход, это было бы здорово.