On Mac and Windows 10, when I used Pyinstaller to run an executable file generated from Python code, I got a ModuleNotFoundError. It is a record when it was avoided.
I used Pyinstaller to generate an executable from my Python code as follows: I am using pipenv.
pipenv run pyinstaller foo.py --onefile
Since the executable file was generated under the dist directory, I moved it as follows.
./dist/foo
A run-time error has occurred. Error message on Mac:
Traceback (most recent call last):
File "site-packages/PyInstaller/loader/rthooks/pyi_rth_pkgres.py", line 13, in <module>
File "/Users/username/.local/share/virtualenvs/foo_project-dA2KfCBr/lib/python3.7/site-packages/PyInstaller/loader/pyimod03_importers.py", line 623, in exec_module
exec(bytecode, module.__dict__)
File "site-packages/pkg_resources/__init__.py", line 86, in <module>
ModuleNotFoundError: No module named 'pkg_resources.py2_warn'
[5125] Failed to execute script pyi_rth_pkgres
Error message on Windows:
Traceback (most recent call last):
File "site-packages\PyInstaller\loader\rthooks\pyi_rth_pkgres.py", line 13, in <module>
File "c:\users\username\.virtualenvs\foo_project-uuzswlzx\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 623, in exec_module
exec(bytecode, module.__dict__)
File "site-packages\pkg_resources\__init__.py", line 86, in <module>
ModuleNotFoundError: No module named 'pkg_resources.py2_warn'
[14256] Failed to execute script pyi_rth_pkgres
This is a workaround. First, when you first run pyinstaller, a .spec file is also generated, so edit it with a text editor. Add the module that has been called ModuleNotFoundError to hidden imports as follows.
foo.spec
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['foo.py'],
pathex=['/Users/username/PycharmProjects/n/foo_project'],
binaries=[],
datas=[],
- hiddenimports=[],
+ hiddenimports=['pkg_resources.py2_warn'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='foo',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True )
Launch pyinstaller again with the edited .spec file, as shown below.
pipenv run pyinstaller foo.spec --onefile
The executable file was generated, so when I moved it as follows, it worked fine.
./dist/foo
The error message contained the following:
exec(bytecode, module.__dict__)
My imagination is that in the executable file generated by pyinstaller, the modules that people installed with pipenv install are not carried over to the code that the exec function runs. You probably need to specify the module in hidden imports in the .spec file for the code that the exec function runs on.
Recommended Posts