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

新手上路,请多包涵

我正在使用 pyinstaller 为我的单个 python 文件生成一个 .exe 文件,但大小超过 30MB,启动速度非常慢。根据我收集到的信息, pyinstaller 默认捆绑了很多不需要的东西。有没有办法确保 pyinstaller 弄清楚只需要什么并只捆绑它们?我的脚本导入部分如下所示:

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

编辑:

或者还有一种方法可以查看它捆绑的所有模块的列表吗?所以我可以通过它们并排除我不需要的那些。

原文由 user9128740 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 677
2 个回答

我最终使用了 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 生成安装程序。

原文由 user9128740 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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 arg 如 这个答案 中解释的那样:

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

原文由 Tsvetomir Batinov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题