Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决

Pyinstaller打包生成的.exe文件过大问题解决

    • 1. 问题摘要
    • 2. 使用原生Python解释器打包
        • (1) Pycharm设置Python解释器路径(已知者可直接跳过)
        • (2) 在原生Python解释器环境下打包
    • 3. 使用Anaconda创建独立Python解释器
    • 4. 使用pipenv创建独立Python解释器
    • 5. 总结

1. 问题摘要

将Python脚本打包成.exe可执行程序的工具有很多,笔者使用的是pyinstaller,命令pyinstaller -F -i RfReportGenTool.ico RfReportGenTool.py。笔者在开发射频指标解析脚本时,发现打包出来的.exe居然有286.616M,如下图。脚本较简单,生成的.exe却这么大,如果你是程序的使用者想必也要心中万马奔腾了。
打包生成exe文件大小图示
检查脚本本身,只导入并使用了如下模块,想必原因不在脚本,而在于打包过程。

import openpyxl
from openpyxl.styles import PatternFill, Border, Side, colors, numbers
from os.path import *
import re
import os
import time
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

检查打包过程如下。笔者使用的是PyCharm+Anaconda的环境,从打包过程看,Anaconda中一些关联库(例如PyQt5、tkinter、matplotlib等等)也被打包导致.exe文件过大,而这些关联库并未使用。那这个问题怎么解决呢?笔者小白一枚,一起学习探索。

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

(base) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>pyinstaller -F -i RfReportGenTool.ico RfReportGenTool.py
90 INFO: PyInstaller: 3.4
90 INFO: Python: 3.7.3
90 INFO: Platform: Windows-7-6.1.7601-SP1
90 INFO: wrote E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\RfReportGenTool.spec
90 INFO: UPX is not available.
90 INFO: Extending PYTHONPATH with paths
['E:\\2_PersonalStudy\\1_PythonStudy\\PythonTool\\RfReportGenTool',
 'E:\\2_PersonalStudy\\1_PythonStudy\\PythonTool\\RfReportGenTool']
90 INFO: checking Analysis
730 INFO: checking PYZ
1121 INFO: checking PKG
1261 INFO: Bootloader C:\ProgramData\Anaconda3\lib\site-packages\PyInstaller\bootloader\Windows-64bit\run.exe
1261 INFO: checking EXE
1290 INFO: Rebuilding EXE-00.toc because RfReportGenTool.exe missing
1301 INFO: Building EXE from EXE-00.toc
1311 INFO: SRCPATH [('RfReportGenTool.ico', None)]
1311 INFO: Updating icons from ['RfReportGenTool.ico'] to C:\Users\ADMINI~1\AppData\Local\Temp\tmp2l25b6j6
1321 INFO: Writing RT_GROUP_ICON 0 resource with 20 bytes
1321 INFO: Writing RT_ICON 1 resource with 67624 bytes
1341 INFO: Appending archive to EXE E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\dist\RfReportGenTool.exe
1790 INFO: Building EXE from EXE-00.toc completed successfully.

(base) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>pyinstaller -F -i RfReportGenTool.ico RfReportGenTool.py
69 INFO: PyInstaller: 3.4
69 INFO: Python: 3.7.3
69 INFO: Platform: Windows-7-6.1.7601-SP1
69 INFO: wrote E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\RfReportGenTool.spec
79 INFO: UPX is not available.
99 INFO: Extending PYTHONPATH with paths
['E:\\2_PersonalStudy\\1_PythonStudy\\PythonTool\\RfReportGenTool',
 'E:\\2_PersonalStudy\\1_PythonStudy\\PythonTool\\RfReportGenTool']
99 INFO: checking Analysis
99 INFO: Building Analysis because Analysis-00.toc is non existent
99 INFO: Initializing module dependency graph...
99 INFO: Initializing module graph hooks...
119 INFO: Analyzing base_library.zip ...
7957 INFO: running Analysis Analysis-00.toc
7977 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by C:\ProgramData\Anaconda3\python.exe
8507 INFO: Caching module hooks...
8518 INFO: Analyzing E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\RfReportGenTool.py
10873 INFO: Processing pre-find module path hook   distutils
11093 INFO: Processing pre-safe import module hook   six.moves
15223 INFO: Processing pre-safe import module hook   setuptools.extern.six.moves
16293 INFO: Processing pre-find module path hook   site
16303 INFO: site: retargeting to fake-dir 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\PyInstaller\\fake-modules'
33863 INFO: Processing pre-safe import module hook   urllib3.packages.six.moves
59037 INFO: Processing pre-safe import module hook   win32com
97071 INFO: Loading module hooks...
97071 INFO: Loading module hook "hook-babel.py"...
97151 INFO: Loading module hook "hook-certifi.py"...
97151 INFO: Loading module hook "hook-cryptography.py"...
97502 INFO: Loading module hook "hook-distutils.py"...
97522 INFO: Loading module hook "hook-docutils.py"...
100486 INFO: Loading module hook "hook-encodings.py"...
100586 INFO: Loading module hook "hook-IPython.py"...
100647 INFO: Excluding import 'PySide'
100657 INFO:   Removing import of PySide from module IPython.external.qt_loaders
100657 INFO: Excluding import 'PyQt4'
100667 INFO:   Removing import of PyQt4 from module IPython.external.qt_loaders
100667 INFO: Excluding import 'PyQt5'
100667 INFO:   Removing import of PyQt5.QtCore from module IPython.external.qt_loaders
100667 INFO:   Removing import of PyQt5.QtWidgets from module IPython.external.qt_loaders
100667 INFO:   Removing import of PyQt5 from module IPython.external.qt_loaders
100667 INFO:   Removing import of PyQt5.QtGui from module IPython.external.qt_loaders
100667 INFO:   Removing import of PyQt5.QtSvg from module IPython.external.qt_loaders
100667 INFO: Excluding import 'tkinter'
100677 INFO:   Removing import of tkinter from module IPython.lib.clipboard
100677 INFO: Excluding import 'gtk'
100677 INFO: Excluding import 'matplotlib'
100687 INFO:   Removing import of matplotlib._pylab_helpers from module IPython.core.pylabtools
100687 INFO:   Removing import of matplotlib from module IPython.core.pylabtools
100687 INFO:   Removing import of matplotlib.pyplot from module IPython.core.pylabtools
100687 INFO:   Removing import of matplotlib.figure from module IPython.core.pylabtools
100687 INFO: Loading module hook "hook-jedi.py"...
100687 INFO: Loading module hook "hook-jinja2.py"...
100746 INFO: Loading module hook "hook-jsonschema.py"...
100757 INFO: Loading module hook "hook-lib2to3.py"...
100777 INFO: Loading module hook "hook-lxml.etree.py"...
100777 INFO: Loading module hook "hook-matplotlib.backends.py"...
101746 INFO:   Matplotlib backend "GTK3Agg": ignored
    cairo backend requires that cairocffi or pycairo is installed
102137 INFO:   Matplotlib backend "GTK3Cairo": ignored
    cairo backend requires that cairocffi or pycairo is installed
102987 INFO:   Matplotlib backend "MacOSX": ignored
    cannot import name '_macosx' from 'matplotlib.backends' (C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\__init__.py)
107239 INFO:   Matplotlib backend "nbAgg": added
107949 INFO:   Matplotlib backend "Qt4Agg": added
108328 INFO:   Matplotlib backend "Qt4Cairo": ignored
    cairo backend requires that cairocffi or pycairo is installed
108854 INFO:   Matplotlib backend "Qt5Agg": added
109203 INFO:   Matplotlib backend "Qt5Cairo": ignored
    cairo backend requires that cairocffi or pycairo is installed
109843 INFO:   Matplotlib backend "TkAgg": added
110314 INFO:   Matplotlib backend "TkCairo": ignored
    cairo backend requires that cairocffi or pycairo is installed
110963 INFO:   Matplotlib backend "WebAgg": added
111414 INFO:   Matplotlib backend "WX": ignored
    No module named 'wx'
111783 INFO:   Matplotlib backend "WXAgg": ignored
    No module named 'wx'
112158 INFO:   Matplotlib backend "WXCairo": ignored
    No module named 'wx'
112539 INFO:   Matplotlib backend "agg": added
112909 INFO:   Matplotlib backend "cairo": ignored
    cairo backend requires that cairocffi or pycairo is installed
113409 INFO:   Matplotlib backend "pdf": added
113861 INFO:   Matplotlib backend "pgf": added
114230 INFO:   Matplotlib backend "ps": added
114611 INFO:   Matplotlib backend "svg": added
115081 INFO:   Matplotlib backend "template": added
115700 INFO: Loading module hook "hook-matplotlib.py"...
116002 INFO: Loading module hook "hook-nacl.py"...
116031 INFO: Loading module hook "hook-numpy.core.py"...
116141 INFO: MKL libraries found when importing numpy. Adding MKL to binaries
116141 INFO: Loading module hook "hook-numpy.py"...
116151 INFO: Loading module hook "hook-openpyxl.py"...
116151 INFO: Loading module hook "hook-pandas.py"...
117286 INFO: Loading module hook "hook-PIL.Image.py"...
117996 INFO: Loading module hook "hook-PIL.py"...
118006 INFO: Excluding import 'PySide'
118006 INFO:   Removing import of PySide from module PIL.ImageQt
118006 INFO: Excluding import 'PyQt4'
118006 INFO:   Removing import of PyQt4 from module PIL.ImageQt
118006 INFO: Excluding import 'tkinter'
118017 INFO:   Removing import of tkinter from module PIL.ImageTk
118017 INFO: Excluding import 'PyQt5'
118017 INFO:   Removing import of PyQt5.QtGui from module PIL.ImageQt
118017 INFO:   Removing import of PyQt5.QtCore from module PIL.ImageQt
118017 INFO: Import to be excluded not found: 'FixTk'
118017 INFO: Loading module hook "hook-PIL.SpiderImagePlugin.py"...
118026 INFO: Excluding import 'tkinter'
118026 INFO: Import to be excluded not found: 'FixTk'
118026 INFO: Loading module hook "hook-pkg_resources.py"...
119137 INFO: Loading module hook "hook-pycparser.py"...
119137 INFO: Loading module hook "hook-pydoc.py"...
119167 INFO: Loading module hook "hook-pygments.py"...
122527 INFO: Loading module hook "hook-PyQt5.py"...
122667 WARNING: Hidden import "PyQt5.sip" not found!
122667 INFO: Loading module hook "hook-PyQt5.QtCore.py"...
122778 WARNING: Unable to find Qt5 translations C:/qt64/qt_1544645195969/_h_env/Library/translations\qtbase_*.qm. These translations were not packaged.
122778 INFO: Loading module hook "hook-PyQt5.QtGui.py"...
122938 WARNING: Unable to find Qt5 translations C:/qt64/qt_1544645195969/_h_env/Library/translations\qtbase_*.qm. These translations were not packaged.
122938 INFO: Loading module hook "hook-PyQt5.QtSvg.py"...
123109 WARNING: Unable to find Qt5 translations C:/qt64/qt_1544645195969/_h_env/Library/translations\qtbase_*.qm. These translations were not packaged.
123109 INFO: Loading module hook "hook-PyQt5.QtWidgets.py"...
123259 WARNING: Unable to find Qt5 translations C:/qt64/qt_1544645195969/_h_env/Library/translations\qtbase_*.qm. These translations were not packaged.
123259 INFO: Loading module hook "hook-pytest.py"...
124905 INFO: Loading module hook "hook-pythoncom.py"...
125425 INFO: Loading module hook "hook-pytz.py"...
125485 INFO: Loading module hook "hook-pywintypes.py"...
125985 INFO: Loading module hook "hook-scipy.linalg.py"...
125985 INFO: Loading module hook "hook-scipy.py"...
125994 INFO: Loading module hook "hook-scipy.sparse.csgraph.py"...
126014 INFO: Loading module hook "hook-scipy.special._ellip_harm_2.py"...
126025 INFO: Loading module hook "hook-scipy.special._ufuncs.py"...
126025 INFO: Loading module hook "hook-setuptools.py"...
126945 INFO: Loading module hook "hook-sphinx.py"...
C:\ProgramData\Anaconda3\lib\site-packages\sphinx\websupport\__init__.py:25: RemovedInSphinx20Warning: sphinx.websupport module is now provided as sphinxcontrib-websupport. sphinx.websupport will be removed
 at Sphinx-2.0. Please use the package instead.
  RemovedInSphinx20Warning)
133282 INFO: Loading module hook "hook-sqlalchemy.py"...
134122 INFO:   Found 4 sqlalchemy hidden imports
134122 WARNING: Hidden import "MySQLdb" not found!
134142 WARNING: Hidden import "sqlalchemy.sql.functions.func" not found!
134142 INFO: Excluding import 'sqlalchemy.testing'
134153 INFO:   Removing import of sqlalchemy.testing.util from module sqlalchemy.orm.util
134153 INFO:   Removing import of sqlalchemy.testing.warnings from module sqlalchemy.testing
134153 INFO:   Removing import of sqlalchemy.testing.assertsql from module sqlalchemy.testing
134153 INFO:   Removing import of sqlalchemy.testing.mock from module sqlalchemy.testing
134153 INFO:   Removing import of sqlalchemy.testing.exclusions from module sqlalchemy.testing
134153 INFO:   Removing import of sqlalchemy.testing.config from module sqlalchemy.testing
134153 INFO:   Removing import of sqlalchemy.testing.assertions from module sqlalchemy.testing
134153 INFO:   Removing import of sqlalchemy.testing.util from module sqlalchemy.testing
134153 INFO:   Removing import of sqlalchemy.testing from module sqlalchemy.testing
134153 INFO:   Removing import of sqlalchemy.testing.engines from module sqlalchemy.testing
134153 INFO:   Removing import of sqlalchemy.testing from module sqlalchemy.testing.config
134153 INFO:   Removing import of sqlalchemy.testing from module sqlalchemy.testing.mock
134153 INFO:   Removing import of sqlalchemy.testing.assertsql from module sqlalchemy.testing.assertions
134153 INFO:   Removing import of sqlalchemy.testing.mock from module sqlalchemy.testing.assertions
134153 INFO:   Removing import of sqlalchemy.testing.exclusions from module sqlalchemy.testing.assertions
134153 INFO:   Removing import of sqlalchemy.testing.config from module sqlalchemy.testing.assertions
134153 INFO:   Removing import of sqlalchemy.testing.util from module sqlalchemy.testing.assertions
134153 INFO:   Removing import of sqlalchemy.testing from module sqlalchemy.testing.assertions
134153 INFO:   Removing import of sqlalchemy.testing from module sqlalchemy.testing.assertsql
134153 INFO:   Removing import of sqlalchemy.testing from module sqlalchemy.testing.util
134153 INFO:   Removing import of sqlalchemy.testing.engines from module sqlalchemy.testing.util
134153 INFO:   Removing import of sqlalchemy.testing.config from module sqlalchemy.testing.util
134153 INFO:   Removing import of sqlalchemy.testing from module sqlalchemy.testing.engines
134153 INFO:   Removing import of sqlalchemy.testing.assertions from module sqlalchemy.testing.engines
134153 INFO:   Removing import of sqlalchemy.testing.util from module sqlalchemy.testing.engines
134153 INFO:   Removing import of sqlalchemy.testing.config from module sqlalchemy.testing.engines
134153 INFO:   Removing import of sqlalchemy.testing from module sqlalchemy.testing.exclusions
134153 INFO:   Removing import of sqlalchemy.testing.config from module sqlalchemy.testing.exclusions
134153 INFO:   Removing import of sqlalchemy.testing.assertions from module sqlalchemy.testing.warnings
134153 INFO:   Removing import of sqlalchemy.testing from module sqlalchemy.testing.warnings
134153 INFO: Loading module hook "hook-sqlite3.py"...
134273 INFO: Loading module hook "hook-sysconfig.py"...
134282 INFO: Loading module hook "hook-tables.py"...
134282 INFO: Loading module hook "hook-win32com.py"...
134483 INFO: Loading module hook "hook-xml.dom.domreg.py"...
134493 INFO: Loading module hook "hook-xml.etree.cElementTree.py"...
134493 INFO: Loading module hook "hook-xml.py"...
134493 INFO: Loading module hook "hook-zmq.py"...
140413 WARNING: Hidden import "file" not found!
140593 WARNING: Hidden import "C:\ProgramData\Anaconda3\lib\site-packages\zmq\backend\cffi\__pycache__\_cffi_ext.c(213):" not found!
140593 WARNING: Hidden import "or" not found!
140593 WARNING: Hidden import "No" not found!
140593 WARNING: Hidden import "fatal" not found!
140593 WARNING: Hidden import "directory" not found!
140593 WARNING: Hidden import "_cffi_ext.c" not found!
140593 WARNING: Hidden import "C1083:" not found!
140593 WARNING: Hidden import "error" not found!
140593 WARNING: Hidden import "????????:" not found!
140593 WARNING: Hidden import ""sys/un.h":" not found!
140593 WARNING: Hidden import "such" not found!
140593 INFO: Loading module hook "hook-_tkinter.py"...
140853 INFO: checking Tree
140853 INFO: Building Tree because Tree-00.toc is non existent
140853 INFO: Building Tree Tree-00.toc
140902 INFO: checking Tree
140902 INFO: Building Tree because Tree-01.toc is non existent
140902 INFO: Building Tree Tree-01.toc
140913 INFO: Loading module hook "hook-gevent.py"...
141322 INFO: Determining a mapping of distributions to packages...
234917 WARNING: Unable to find package for requirement greenlet from package gevent.
234917 INFO: Packages required by gevent:
['cffi']
236826 INFO: Looking for ctypes DLLs
236975 INFO: Analyzing run-time hooks ...
236995 INFO: Including run-time hook 'pyi_rth_multiprocessing.py'
237006 INFO: Including run-time hook 'pyi_rth_pkgres.py'
237015 INFO: Including run-time hook 'pyi_rth_win32comgenpy.py'
237026 INFO: Including run-time hook 'pyi_rth_traitlets.py'
237036 INFO: Including run-time hook 'pyi_rth__tkinter.py'
237036 INFO: Including run-time hook 'pyi_rth_qt5.py'
237046 INFO: Including run-time hook 'pyi_rth_mplconfig.py'
237055 INFO: Including run-time hook 'pyi_rth_mpldata.py'
237115 INFO: Looking for dynamic libraries
237275 WARNING: lib not found: pgf90rtl.dll dependency of C:\ProgramData\Anaconda3\Library\bin\mkl_pgi_thread.dll
237345 WARNING: lib not found: pgf90.dll dependency of C:\ProgramData\Anaconda3\Library\bin\mkl_pgi_thread.dll
237415 WARNING: lib not found: pgc14.dll dependency of C:\ProgramData\Anaconda3\Library\bin\mkl_pgi_thread.dll
237735 WARNING: lib not found: mpich2mpi.dll dependency of C:\ProgramData\Anaconda3\Library\bin\mkl_blacs_mpich2_lp64.dll
238187 WARNING: lib not found: msmpi.dll dependency of C:\ProgramData\Anaconda3\Library\bin\mkl_blacs_msmpi_ilp64.dll
238467 WARNING: lib not found: impi.dll dependency of C:\ProgramData\Anaconda3\Library\bin\mkl_blacs_intelmpi_ilp64.dll
238766 WARNING: lib not found: mpich2mpi.dll dependency of C:\ProgramData\Anaconda3\Library\bin\mkl_blacs_mpich2_ilp64.dll
238917 WARNING: lib not found: impi.dll dependency of C:\ProgramData\Anaconda3\Library\bin\mkl_blacs_intelmpi_lp64.dll
239117 WARNING: lib not found: msmpi.dll dependency of C:\ProgramData\Anaconda3\Library\bin\mkl_blacs_msmpi_lp64.dll
242941 INFO: Looking for eggs
242941 INFO: Using Python library C:\ProgramData\Anaconda3\python37.dll
242941 INFO: Found binding redirects:
[]
242971 INFO: Warnings written to E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\build\RfReportGenTool\warn-RfReportGenTool.txt
243502 INFO: Graph cross-reference written to E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\build\RfReportGenTool\xref-RfReportGenTool.html
243691 INFO: checking PYZ
243691 INFO: Building PYZ because PYZ-00.toc is non existent
243691 INFO: Building PYZ (ZlibArchive) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\build\RfReportGenTool\PYZ-00.pyz
249215 INFO: Building PYZ (ZlibArchive) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\build\RfReportGenTool\PYZ-00.pyz completed successfully.
249325 INFO: checking PKG
249325 INFO: Building PKG because PKG-00.toc is non existent
249325 INFO: Building PKG (CArchive) PKG-00.pkg
365265 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
365355 INFO: Bootloader C:\ProgramData\Anaconda3\lib\site-packages\PyInstaller\bootloader\Windows-64bit\run.exe
365355 INFO: checking EXE
365355 INFO: Building EXE because EXE-00.toc is non existent
365355 INFO: Building EXE from EXE-00.toc
365405 INFO: SRCPATH [('RfReportGenTool.ico', None)]
365405 INFO: Updating icons from ['RfReportGenTool.ico'] to C:\Users\ADMINI~1\AppData\Local\Temp\tmpje0_435i
365434 INFO: Writing RT_GROUP_ICON 0 resource with 20 bytes
365434 INFO: Writing RT_ICON 1 resource with 67624 bytes
365454 INFO: Appending archive to EXE E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\dist\RfReportGenTool.exe
365734 INFO: Building EXE from EXE-00.toc completed successfully.

(base) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>

2. 使用原生Python解释器打包

笔者使用的环境是Pycharm+Anaconda,既然Anaconda会将不需要的关联库同时打包,那我们可以尝试使用原生Python解释器。后文均使用PyCharm进行操作,当然读者也可以通过修改环境变量的方式在cmd下执行,灵活运用。

(1) Pycharm设置Python解释器路径(已知者可直接跳过)

Step 1: 依次点击File=>Settings(或快捷键Ctrl+Alt+S),打开Settings选项卡。
Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决_第1张图片
Step 2: 依次点击Project XXX=>Project Interpreter(XXX为项目名称),可以看到当前使用的Python解释器和安装的包;继续点击设置=>Add,打开Add Python Interpreter选项卡。
Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决_第2张图片
Step 3: 按照下图中1和2操作,打开Select Python Interpreter选项卡;选择原生Python解释器路径(读者需使用自己安装的Python解释器路径,图中是笔者的路径),并依次点击OK。
Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决_第3张图片
Step 4: 下图中可以查看原生Python解释器安装的包,明显比Anaconda要少得多,既然没有多余的关联库,也就不会被打包;点击Apply=>OK,等待加载完成即可。
Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决_第4张图片

(2) 在原生Python解释器环境下打包

Python解释器路径修改完成后,需要重新开启Pycharm中的Terminal,可以使用where python命令查看一下当前的Python路径。另外,由于笔者的脚本中使用了openpyxl且打包时需要使用pyinstaller,而原生python解释器中并未安装,需要安装所有用到的模块才能正常打包。以下是笔者使用pip安装openpyxl和pyinstaller的过程。

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>where python
C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\python.exe

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>
E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>pip install openpyxl
Processing c:\users\administrator\appdata\local\pip\cache\wheels\41\ba\1e\266431033670ab5b010a3eddba51cf1a6dc5cbc7231e32f464\openpyxl-3.0.2-py2.py3-none-any.whl
Requirement already satisfied: jdcal in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from openpyxl) (1.4.1)
Requirement already satisfied: et-xmlfile in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from openpyxl) (1.0.1)
Installing collected packages: openpyxl
Successfully installed openpyxl-3.0.2

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>pip install pyinstaller
Processing c:\users\administrator\appdata\local\pip\cache\wheels\c6\a4\e0\d9a1c5d3d876eb0675171281c293aed80839115e2eb022e6d2\pyinstaller-3.5-cp37-none-any.whl
Requirement already satisfied: pywin32-ctypes>=0.2.0 in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from pyinstaller) (0.2.0)
Requirement already satisfied: setuptools in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from pyinstaller) (40.8.0)
Requirement already satisfied: altgraph in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from pyinstaller) (0.16.1)
Requirement already satisfied: pefile>=2017.8.1 in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from pyinstaller) (2019.4.18)
Requirement already satisfied: future in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from pefile>=2017.8.1->pyinstaller) (0.18.2)
Installing collected packages: pyinstaller
Successfully installed pyinstaller-3.5

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>

再次进行打包,会发现整个打包过程简化了很多,并且输出的.exe文件只有5.926M,达到了目的。原生Python解释器比较干净,但是随着功能的增加,库也会越来越多。我们是否可以在项目开始前就新建独立的Python解释器环境,然后只安装项目需要的库呢?接下来一起学习使用Anaconda和pipenv创建独立的Python解释器。
原生Python解释器打包大小

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>pyinstaller -F -i RfReportGenTool.ico RfReportGenTool.py
320 INFO: PyInstaller: 3.5
320 INFO: Python: 3.7.3
320 INFO: Platform: Windows-7-6.1.7601-SP1
320 INFO: wrote E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\RfReportGenTool.spec
320 INFO: UPX is not available.
330 INFO: Extending PYTHONPATH with paths
['E:\\2_PersonalStudy\\1_PythonStudy\\PythonTool\\RfReportGenTool',
 'E:\\2_PersonalStudy\\1_PythonStudy\\PythonTool\\RfReportGenTool']
330 INFO: checking Analysis
330 INFO: Building Analysis because Analysis-00.toc is non existent
330 INFO: Initializing module dependency graph...
330 INFO: Initializing module graph hooks...
330 INFO: Analyzing base_library.zip ...
4992 INFO: running Analysis Analysis-00.toc
5022 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by c:\users\administrator\appdata\local\programs\python\python37-32\python.exe
5473 INFO: Caching module hooks...
5483 INFO: Analyzing E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\RfReportGenTool.py
6635 INFO: Loading module hooks...
6635 INFO: Loading module hook "hook-encodings.py"...
6835 INFO: Loading module hook "hook-openpyxl.py"...
6845 INFO: Loading module hook "hook-pydoc.py"...
6845 INFO: Loading module hook "hook-xml.etree.cElementTree.py"...
6845 INFO: Loading module hook "hook-xml.py"...
7195 INFO: Looking for ctypes DLLs
7195 INFO: Analyzing run-time hooks ...
7204 INFO: Looking for dynamic libraries
7496 INFO: Looking for eggs
7496 INFO: Using Python library c:\users\administrator\appdata\local\programs\python\python37-32\python37.dll
7496 INFO: Found binding redirects:
[]
7526 INFO: Warnings written to E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\build\RfReportGenTool\warn-RfReportGenTool.txt
7596 INFO: Graph cross-reference written to E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\build\RfReportGenTool\xref-RfReportGenTool.html
7626 INFO: checking PYZ
7626 INFO: Building PYZ because PYZ-00.toc is non existent
7626 INFO: Building PYZ (ZlibArchive) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\build\RfReportGenTool\PYZ-00.pyz
8216 INFO: Building PYZ (ZlibArchive) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\build\RfReportGenTool\PYZ-00.pyz completed successfully.
8236 INFO: checking PKG
8236 INFO: Building PKG because PKG-00.toc is non existent
8236 INFO: Building PKG (CArchive) PKG-00.pkg
10499 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
10499 INFO: Bootloader c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages\PyInstaller\bootloader\Windows-32bit\run.exe
10499 INFO: checking EXE
10499 INFO: Building EXE because EXE-00.toc is non existent
10499 INFO: Building EXE from EXE-00.toc
10539 INFO: Copying icons from ['RfReportGenTool.ico']
10559 INFO: Writing RT_GROUP_ICON 0 resource with 20 bytes
10559 INFO: Writing RT_ICON 1 resource with 67624 bytes
10628 INFO: Updating manifest in C:\Users\ADMINI~1\AppData\Local\Temp\tmpdnfirr_c
10628 INFO: Updating resource type 24 name 1 language 0
10669 INFO: Appending archive to EXE E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\dist\RfReportGenTool.exe
10679 INFO: Building EXE from EXE-00.toc completed successfully.

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>

3. 使用Anaconda创建独立Python解释器

本文介绍的Anaconda环境的创建和管理是通过图形界面完成的,当然也可以使用conda相关命令,更加灵活,这里不做介绍。通过Anaconda创建独立Python解释器环境的具体步骤如下:

Step 1: 打开Anaconda后,依次按照图示步骤进行。依次点击Environments=>Create,打开Create new environment选项卡,填写Name(自定义)和版本等相关信息,最后点击Create;其中,图示3部分是默认的路径,该路径用于后续修改PyCharm中的解释器环境。
Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决_第5张图片
Step 2: 等待创建完成,界面下方有进度条显示。
Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决_第6张图片
Step 3: 成功后会在Environments中显示刚刚创建的环境Name,右边是默认安装的一些基础包,到这里新的Python解释器环境便创建完成。当然,为了实现笔者脚本的打包,还需要安装pyinstaller和openpyxl,所以继续后面的步骤。
Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决_第7张图片
Step 4: 按照图示步骤安装pyinstaller和openpyxl及其相关包。
Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决_第8张图片
Python打包成.exe程序:Pyinstaller打包生成的.exe文件过大问题解决_第9张图片
Step 5: 同上文一样,修改PyCharm中解释器路径为Anaconda新建环境路径,并用pyinstaller打包,结果如下图所示,大小6.876M,同样达成目的。
Anaconda新建解释器打包大小


4. 使用pipenv创建独立Python解释器

在查找相关资料时,发现使用pipenv同样可以创建独立的Python解释器环境,具体过程如下:

Step 1: 首先要安装pipenv。安装命令pip install pipenv,并可通过pip list命令查看安装的包。

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>pip install pipenv
Collecting pipenv
  Using cached https://files.pythonhosted.org/packages/13/b4/3ffa55f77161cff9a5220f162670f7c5eb00df52e00939e203f601b0f579/pipenv-2018.11.26-py3-n
one-any.whl
Requirement already satisfied: virtualenv in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from pipenv) (16
.7.8)
Requirement already satisfied: virtualenv-clone>=0.2.5 in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (fro
m pipenv) (0.5.3)
Requirement already satisfied: setuptools>=36.2.1 in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from pip
env) (40.8.0)
Requirement already satisfied: pip>=9.0.1 in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from pipenv) (19
.3.1)
Requirement already satisfied: certifi in c:\users\administrator\appdata\local\programs\python\python37-32\lib\site-packages (from pipenv) (2019.
11.28)
Installing collected packages: pipenv
Successfully installed pipenv-2018.11.26

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>
E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>pip list
Package          Version
---------------- ----------
altgraph         0.16.1
certifi          2019.11.28
et-xmlfile       1.0.1
future           0.18.2
jdcal            1.4.1
openpyxl         3.0.2
pefile           2019.4.18
pip              19.3.1
pipenv           2018.11.26
PyInstaller      3.5
pywin32-ctypes   0.2.0
setuptools       40.8.0
virtualenv       16.7.8
virtualenv-clone 0.5.3

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>

Step 2: 选择合适的路径创建环境(读者自定义),笔者的路径是E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv;进入该路径,执行pipenv install --python 3.7命令创建虚拟环境,其中3.7是笔者使用的版本(读者自定义),成功后路径下会生成Pipfile和Pipfile.lock两个文件。

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool>cd TestEnv

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>pipenv install --python 3.7
Creating a virtualenv for this project…
Pipfile: E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv\Pipfile
Using C:/Users/Administrator/AppData/Local/Programs/Python/Python37-32/python.exe (3.7.3) to create virtualenv…
[ ===] Creating virtual environment...Already using interpreter C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\python.exe
Using base prefix 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37-32'
New python executable in C:\Users\Administrator\.virtualenvs\TestEnv-gIDENZIq\Scripts\python.exe
Installing setuptools, pip, wheel...
done.
Running virtualenv with interpreter C:/Users/Administrator/AppData/Local/Programs/Python/Python37-32/python.exe

Successfully created virtual environment!
Virtualenv location: C:\Users\Administrator\.virtualenvs\TestEnv-gIDENZIq
Creating a Pipfile for this project…
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Updated Pipfile.lock (a65489)!
Installing dependencies from Pipfile.lock (a65489)================================ 0/0 - 00:00:00
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>

Step 3: 激活环境,命令是pipenv shell;然后可以使用pip list命令查看到里面只有很少的库,同时也说明成功进入了虚拟环境。

E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>pipenv shell
Launching subshell in virtual environment…
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

(TestEnv-gIDENZIq) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>
(TestEnv-gIDENZIq) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>pip list
Package    Version
---------- -------
pip        19.3.1
setuptools 42.0.2
wheel      0.33.6

(TestEnv-gIDENZIq) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>

Step 4: 同上文一样,在新建环境中安装笔者所需要的pyinstaller和openpyxl包。

(TestEnv-gIDENZIq) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>pip install openpyxl
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read ti
meout=15)")': /simple/openpyxl/
Processing c:\users\administrator\appdata\local\pip\cache\wheels\41\ba\1e\266431033670ab5b010a3eddba51cf1a6dc5cbc7231e32f464\openpyxl-3.0.2-py2.py3-none-any.whl
Collecting jdcal
  Using cached https://files.pythonhosted.org/packages/f0/da/572cbc0bc582390480bbd7c4e93d14dc46079778ed915b505dc494b37c57/jdcal-1.4.1-py2.py3-none-any.whl
Processing c:\users\administrator\appdata\local\pip\cache\wheels\2a\77\35\0da0965a057698121fc7d8c5a7a9955cdbfb3cc4e2423cad39\et_xmlfile-1.0.1-cp37-none-any.whl
Installing collected packages: jdcal, et-xmlfile, openpyxl
Successfully installed et-xmlfile-1.0.1 jdcal-1.4.1 openpyxl-3.0.2

(TestEnv-gIDENZIq) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>
(TestEnv-gIDENZIq) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>pip install pyinstaller
Processing c:\users\administrator\appdata\local\pip\cache\wheels\c6\a4\e0\d9a1c5d3d876eb0675171281c293aed80839115e2eb022e6d2\pyinstaller-3.5-cp37-none-any.whl
Collecting altgraph
  Using cached https://files.pythonhosted.org/packages/0a/cc/646187eac4b797069e2e6b736f14cdef85dbe405c9bfc7803ef36e4f62ef/altgraph-0.16.1-py2.py3-none-any.whl
Processing c:\users\administrator\appdata\local\pip\cache\wheels\1c\a1\95\4f33011a0c013c872fe6f0f364dc463a2588120820e40a30d8\pefile-2019.4.18-cp37-none-any.whl
Collecting pywin32-ctypes>=0.2.0
  Using cached https://files.pythonhosted.org/packages/9e/4b/3ab2720f1fa4b4bc924ef1932b842edf10007e4547ea8157b0b9fc78599a/pywin32_ctypes-0.2.0-py2.py3-none-any.whl
Requirement already satisfied: setuptools in c:\users\administrator\.virtualenvs\testenv-gidenziq\lib\site-packages (from pyinstaller) (42.0.2)
Processing c:\users\administrator\appdata\local\pip\cache\wheels\8b\99\a0\81daf51dcd359a9377b110a8a886b3895921802d2fc1b2397e\future-0.18.2-cp37-none-any.whl
Installing collected packages: altgraph, future, pefile, pywin32-ctypes, pyinstaller
Successfully installed altgraph-0.16.1 future-0.18.2 pefile-2019.4.18 pyinstaller-3.5 pywin32-ctypes-0.2.0

(TestEnv-gIDENZIq) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>

Step 5: 笔者将原Python脚本放入该环境路径下,并进行打包,打包的结果和过程如下所示,同样达成目的。
pipenv新建解释器打包大小

(TestEnv-gIDENZIq) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>pyinstaller -F -i RfReportGenTool.ico RfReportGenTool.py
200 INFO: PyInstaller: 3.5
200 INFO: Python: 3.7.3
200 INFO: Platform: Windows-7-6.1.7601-SP1
200 INFO: wrote E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv\RfReportGenTool.spec
200 INFO: UPX is not available.
200 INFO: Extending PYTHONPATH with paths
['E:\\2_PersonalStudy\\1_PythonStudy\\PythonTool\\RfReportGenTool\\TestEnv',
 'E:\\2_PersonalStudy\\1_PythonStudy\\PythonTool\\RfReportGenTool\\TestEnv']
200 INFO: checking Analysis
200 INFO: Building Analysis because Analysis-00.toc is non existent
200 INFO: Initializing module dependency graph...
200 INFO: Initializing module graph hooks...
210 INFO: Analyzing base_library.zip ...
4084 INFO: running Analysis Analysis-00.toc
4133 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by c:\users\administrator\.virtualenvs\testenv-gidenziq\scripts\python.exe
4493 INFO: Caching module hooks...
4503 INFO: Analyzing E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv\RfReportGenTool.py
5667 INFO: Loading module hooks...
5667 INFO: Loading module hook "hook-encodings.py"...
5837 INFO: Loading module hook "hook-openpyxl.py"...
5848 INFO: Loading module hook "hook-pydoc.py"...
5848 INFO: Loading module hook "hook-xml.etree.cElementTree.py"...
5848 INFO: Loading module hook "hook-xml.py"...
6208 INFO: Looking for ctypes DLLs
6208 INFO: Analyzing run-time hooks ...
6217 INFO: Looking for dynamic libraries
6449 INFO: Looking for eggs
6449 INFO: Using Python library c:\users\administrator\.virtualenvs\testenv-gidenziq\scripts\python37.dll
6449 INFO: Found binding redirects:
[]
6449 INFO: Warnings written to E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv\build\RfReportGenTool\warn-RfReportGenTool.txt
6529 INFO: Graph cross-reference written to E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv\build\RfReportGenTool\xref-RfReportGenTool.html
6588 INFO: checking PYZ
6588 INFO: Building PYZ because PYZ-00.toc is non existent
6588 INFO: Building PYZ (ZlibArchive) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv\build\RfReportGenTool\PYZ-00.pyz
7278 INFO: Building PYZ (ZlibArchive) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv\build\RfReportGenTool\PYZ-00.pyz completed successfully.
7289 INFO: checking PKG
7289 INFO: Building PKG because PKG-00.toc is non existent
7289 INFO: Building PKG (CArchive) PKG-00.pkg
9580 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
9580 INFO: Bootloader c:\users\administrator\.virtualenvs\testenv-gidenziq\lib\site-packages\PyInstaller\bootloader\Windows-32bit\run.exe
9580 INFO: checking EXE
9580 INFO: Building EXE because EXE-00.toc is non existent
9580 INFO: Building EXE from EXE-00.toc
9620 INFO: Copying icons from ['RfReportGenTool.ico']
9640 INFO: Writing RT_GROUP_ICON 0 resource with 20 bytes
9640 INFO: Writing RT_ICON 1 resource with 67624 bytes
9690 INFO: Updating manifest in C:\Users\ADMINI~1\AppData\Local\Temp\tmpykcti9nt
9690 INFO: Updating resource type 24 name 1 language 0
9730 INFO: Appending archive to EXE E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv\dist\RfReportGenTool.exe
9740 INFO: Building EXE from EXE-00.toc completed successfully.

(TestEnv-gIDENZIq) E:\2_PersonalStudy\1_PythonStudy\PythonTool\RfReportGenTool\TestEnv>

5. 总结

  1. 通过pyinstaller打包Python脚本,生成的.exe文件有时过大,原因是默认打包了一些并未使用的关联库。我们可以在项目开始前,使用Anaconda或者pipenv创建独立的Python解释器环境,仅安装项目所需要的包,这样就不会导致生成的.exe文件过大。
  2. 笔者小白一枚,此文档仅用于Python学习记录和交流,如能帮助到读者倍感荣幸。

你可能感兴趣的:(Python,python,anaconda,exe)