如何在 pyinstaller 中只包含需要的模块?

How to include only needed modules in pyinstaller?

我正在使用 pyinstaller 为我的单个 python 文件生成一个 .exe 文件,但是大小超过 30MB,而且启动非常慢。据我所知,pyinstaller 默认捆绑了很多不需要的东西。有没有办法确保 pyinstaller 找出只需要的东西并只捆绑它们?我的脚本导入部分如下所示:

import datetime
import os
import numpy as np
import pandas as pd 
import xlsxwriter
from tkinter import *

编辑:

或者有没有办法查看它捆绑的所有模块的列表?所以我可以通过它们并排除我不需要的。

我认为它无法为您解决这个问题。如果有任何特定模块需要一段时间才能加载,请使用 --exclude-module 标志列出您要排除的所有模块。

编辑:this answer 可能有一些更有帮助的信息

为此您需要创建一个单独的环境,因为当前您正在读取计算机上安装的所有模块。 创建环境 运行 命令

1 - 如果您没有,请创建一个 requirements.txt 文件,其中包含您正在使用的所有包,您可以创建一个:

pip freeze > requirements.txt

2 - 创建环境文件夹:

python -m venv projectName

3 - 激活环境:

source projectName/bin/activate

4 - 安装它们:

pip install -r requirements.txt

或者,如果你知道你只使用 wxpython,你可以 pip install wxpython

5 - 最后你可以 运行 pyinstaller 在你的主脚本上使用 --path 参数,如 this answer:

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

最后我用了cx_Freeze。它似乎比 py2exepyinstaller 工作得更好。我编写了 setup.py 如下所示的文件:

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)

任何人都可以 运行 python setup.py build_exe 生成可执行文件或 python setup.py bdist_msi 生成安装程序。