How to include only needed modules in pyinstaller?

For this you need to create a separate environment, because currently you are reading all the modules you have installed on your computer. To create environment run commands

1 - if you don't have one, create a requirements.txt file that holds all packages that you are using, you could create one with:

pip freeze > requirements.txt

2 - create env folder:

python -m venv projectName

3 - activate the environment:

source projectName/bin/activate

4 - install them:

pip install -r requirements.txt

alternatively if you know you are using only wxpython you could just pip install wxpython

5 - then finally you can run pyinstaller on your main script with the --path arg as explained in this answer:

pyinstaller --paths projectName/lib/python3.7/site-packages script.py

I ended up using cx_Freeze in the end. It seems to work much better than py2exe or pyinstaller. I wrote setup.py file that looks like this:

import os
import shutil
import sys
from cx_Freeze import setup, Executable

os.environ['TCL_LIBRARY'] = r'C:\bin\Python37-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\bin\Python37-32\tcl\tk8.6'

__version__ = '1.0.0'
base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

include_files = ['am.png']
includes = ['tkinter']
excludes = ['matplotlib', 'sqlite3']
packages = ['numpy', 'pandas', 'xlsxwriter']

setup(
    name='TestApp',
    description='Test App',
    version=__version__,
    executables=[Executable('test.py', base=base)],
    options = {'build_exe': {
        'packages': packages,
        'includes': includes,
        'include_files': include_files,
        'include_msvcr': True,
        'excludes': excludes,
    }},
)

path = os.path.abspath(os.path.join(os.path.realpath(__file__), os.pardir))
build_path = os.path.join(path, 'build', 'exe.win32-3.7')
shutil.copy(r'C:\bin\Python37-32\DLLs\tcl86t.dll', build_path)
shutil.copy(r'C:\bin\Python37-32\DLLs\tk86t.dll', build_path)

Any then one can either run python setup.py build_exe to generate an executable or python setup.py bdist_msi to generate an installer.


I don't think it can figure that out for you. If there are any specific modules taking a while to load, use the --exclude-module flag to list all the modules you want to exclude.

edit: this answer may have some more helpful info