简体   繁体   English

如何使用 pyinstaller 创建最小大小的可执行文件?

[英]How can I create the minimum size executable with pyinstaller?

I am on Windows 10, I have anaconda installed but I want to create an executable independently in a new, clean minimal environment using python 3.5.我在 Windows 10 上,我安装了 anaconda,但我想使用 python 3.5 在一个新的、干净的最小环境中独立创建一个可执行文件。 So I did some tests:所以我做了一些测试:

TEST1: I created a python script test1.py in the folder testenv with only: TEST1:我在文件夹 testenv 中创建了一个 python 脚本 test1.py,只有:

print('Hello World')

Then I created the environment, installed pyinstaller and created the executable然后我创建了环境,安装了pyinstaller并创建了可执行文件

D:\testenv> python -m venv venv_test
...
D:\testenv\venv_test\Scripts>activate.bat
...
(venv_test) D:\testenv>pip install pyinstaller
(venv_test) D:\testenv>pyinstaller --clean -F test1.py

And it creates my test1.exe of about 6 Mb它创建了我的 test1.exe 大约 6 Mb

TEST 2: I modified test1.py as follows:测试 2:我修改 test1.py 如下:

import pandas as pd
print('Hello World')  

I installed pandas in the environment and created the new executable:我在环境中安装了 pandas 并创建了新的可执行文件:

(venv_test) D:\testenv>pip install pandas
(venv_test) D:\testenv>pyinstaller --clean -F test1.py

Ant it creates my test1.exe which is now of 230 Mb !!! Ant 它创建了我的 test1.exe,它现在是230 Mb !!!

if I run the command如果我运行命令

(venv_test) D:\testenv>python -V
Python 3.5.2 :: Anaconda custom (64-bit)

when I am running pyinstaller I get some messages I do not understand, for example:当我运行 pyinstaller 时,我收到一些我不明白的消息,例如:

INFO: site: retargeting to fake-dir 'c:\\users\\username\\appdata\\local\\continuum\\anaconda3\\lib\\site-packages\\PyInstaller\\fake-modules'

Also I am getting messages about matplotlib and other modules that have nothing to do with my code, for example:此外,我收到有关 matplotlib 和其他与我的代码无关的模块的消息,例如:

INFO:   Matplotlib backend "pdf": added
INFO:   Matplotlib backend "pgf": added
INFO:   Matplotlib backend "ps": added
INFO:   Matplotlib backend "svg": added

I know there are some related questions: Reducing size of pyinstaller exe , size of executable using pyinstaller and numpy but I could not solve the problem and I am afraid I am doing something wrong with respect to anaconda.我知道有一些相关的问题: 减少 pyinstaller exe 的大小,使用 pyinstaller 和 numpy 的可执行文件的大小,但我无法解决问题,恐怕我在 anaconda 方面做错了。

So my questions are: what am I doing wrong?所以我的问题是:我做错了什么? can I reduce the size of my executable?我可以减少可执行文件的大小吗?

I accepted the answer above but I post here what I did step by step for complete beginners like me who easily get lost.我接受了上面的答案,但我在这里发布了我为像我这样容易迷路的完全初学者一步一步做的事情。

Before I begin I post my complete test1.py example script with all the modules I actually need.在开始之前,我发布了包含我实际需要的所有模块的完整 test1.py 示例脚本。 My apologies if it is a bit more complex than the original question but maybe this can help someone.如果它比原始问题更复杂一点,我深表歉意,但也许这可以帮助某人。

test1.py looks like this: test1.py 看起来像这样:

import matplotlib 
matplotlib.use('Agg') 
import matplotlib.pyplot as plt
import matplotlib.image as image
import numpy as np
import os.path
import pandas as pd
import re   

from matplotlib.ticker import AutoMinorLocator 
from netCDF4 import Dataset
from time import time
from scipy.spatial import distance
from simpledbf import Dbf5
from sys import argv

print('Hello World')

I added matplotlib.use('Agg') (as my actual code is creating figures) Generating a PNG with matplotlib when DISPLAY is undefined我添加了 matplotlib.use('Agg') (因为我的实际代码正在创建数字) 当 DISPLAY 未定义时用 matplotlib 生成一个 PNG

1) Install a new version of python independently from anaconda. 1)独立于anaconda安装新版本的python。

downloaded python from: https://www.python.org/downloads/ installed selecting 'add python to path' and deselecting install launcher for all users (I don't have admin rights) check that I am using the same version from CMD, just writing python I get: Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.从以下位置下载 python: https : //www.python.org/downloads/安装 选择“将 python 添加到路径”并为所有用户取消选择安装启动器(我没有管理员权限)检查我是否使用了来自 CMD 的相同版本, 只是写python我得到:Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type“help”,“copyright”, “学分”或“许可证”以获取更多信息。

2) Create and activate the environment, from CMD 2)从CMD创建并激活环境

D:\> mkdir py36envtest
...
D:\py36envtest>python -m venv venv_py36
...
D:\py36envtest\venv_py36\Scripts>activate.bat

3) Install in the environment all the modules needed in the script 3)在环境中安装脚本中需要的所有模块

Making sure they are compatible to the python version with the command: (from Matplotlib not recognized as a module when importing in Python )使用以下命令确保它们与 python 版本兼容:(从Matplotlib 在 Python 中导入时未被识别为模块

(venv_py36) D:\py36envtest> python -m pip install nameofmodule

NB: in my case I also had to add the option --proxy https://00.000.000.00:0000注意:就我而言,我还必须添加选项 --proxy https://00.000.000.00:0000

for the example I used development version of py installer:例如,我使用了 py 安装程序的开发版本:

(venv_py36) D:\py36envtest> python -m pip install https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz

and the modules: pandas, matplolib, simpledbf, scipy, netCDF4.和模块:pandas、matplolib、simpledbf、scipy、netCDF4。 At the end my environment looks like this.最后我的环境看起来像这样。

(venv_py36) D:\py36envtest> pip freeze
altgraph==0.15
cycler==0.10.0
future==0.16.0
macholib==1.9
matplotlib==2.1.2
netCDF4==1.3.1
numpy==1.14.0
pandas==0.22.0
pefile==2017.11.5
PyInstaller==3.4.dev0+5f9190544
pyparsing==2.2.0
pypiwin32==220
python-dateutil==2.6.1
pytz==2017.3
scipy==1.0.0
simpledbf==0.2.6
six==1.11.0
style==1.1.0
update==0.0.1

4) Create/modify the .spec file (when you run pyinstaller it creates a .spec file, you can rename). 4) 创建/修改 .spec 文件(当您运行 pyinstaller 时,它会创建一个 .spec 文件,您可以重命名)。

Initially I got a lot of ImportError: DLL load failed (especially for scipy) and missing module error which I solved thanks to these posts:最初,我遇到了很多 ImportError: DLL load failed (特别是对于 scipy) 和缺少模块错误,由于这些帖子,我解决了这些错误:
What is the recommended way to persist (pickle) custom sklearn pipelines? 持久化(pickle)自定义 sklearn 管道的推荐方法是什么?
and the comment to this answer: Pyinstaller with scipy.signal ImportError: DLL load failed以及对此答案的评论: Pyinstaller with scipy.signal ImportError: DLL load failed

My inputtest1.spec finally looks like this:我的 inputtest1.spec 最终看起来像这样:

# -*- mode: python -*-
options = [ ('v', None, 'OPTION')]
block_cipher = None


a = Analysis(['test1.py'],
             pathex=['D:\\py36envtest', 'D:\\py36envtest\\venv_py36\\Lib\\site-packages\\scipy\\extra-dll' ],
             binaries=[],
             datas=[],
             hiddenimports=['scipy._lib.messagestream',
                            'pandas._libs.tslibs.timedeltas'],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='test1',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

5) Finally make the executable with the command 5)最后用命令制作可执行文件

(venv_py36) D:\py36envtest>pyinstaller -F --clean inputtest1.spec

my test1.exe is 47.6 Mb, the .exe of the same script created from an anaconda virtual environment is 229 Mb.我的 test1.exe 是 47.6 Mb,从 anaconda 虚拟环境创建的相同脚本的 .exe 是 229 Mb。

I am happy (and if there are more suggestions they are welcome)我很高兴(如果有更多建议,欢迎提出)

The problem is that you should not be using a virtual environment and especially not anaconda.问题是您不应该使用虚拟环境,尤其是 anaconda。 Please download default python 32 bit and use only necessary modules.请下载默认的 python 32 位并仅使用必要的模块。 Then follow the steps provided in the links, this should definitely fix it.然后按照链接中提供的步骤进行操作,这肯定会解决它。

Although you created a virtual env, are you sure your spec file is not linking to old Anaconda entries?尽管您创建了一个虚拟环境,但您确定您的规范文件没有链接到旧的 Anaconda 条目吗?

If all this fails, then submit a bug as this is very strange.如果这一切都失败了,那么提交一个错误,因为这很奇怪。

I had a similar problem and found a solution.我遇到了类似的问题并找到了解决方案。

I used Windows terminal preview.我使用了 Windows 终端预览。 This program allows creation of various virtual environments like Windows Power Shell (btw. Linux Ubuntu too. Also, worth noting: you can have many terminals in this program installed and, even, open a few at once. Very cool stuff).该程序允许创建各种虚拟环境,例如 Windows Power Shell(顺便说一句。Linux Ubuntu 也是如此。另外,值得注意的是:您可以在该程序中安装多个终端,甚至一次打开几个。非常酷的东西)。

Inside Windows Power Shell in Windows terminal preview I installed all the necessary libraries (like numpy, pandas,re, etc.), then I opened the path to my file and tried to use this command:在 Windows 终端预览中的 Windows Power Shell 中,我安装了所有必要的库(如 numpy、pandas、re 等),然后打开文件路径并尝试使用以下命令:

pyinstaller --onefile -w 'filename.py' pyinstaller --onefile -w '文件名.py'

...but, the output exe didn't work. ...但是,输出exe不起作用。 For some reason, the console said that there is a lack of one library (which I had installed earlier).出于某种原因,控制台说缺少一个库(我之前安装过)。 I've found the solution in mimic the auto-py-to-exe library.我在模拟auto-py-to-exe库中找到了解决方案。 The command used by this GUI is:此 GUI 使用的命令是:

pyinstaller --noconfirm --onedir --console "C:/Users/something/filename.py"

And this one works well.而这个效果很好。 I reduced the size of my output exe program from 911MB to 82,9MB !!!我将输出 exe 程序的大小从 911MB 减少到 82,9MB !!!

BTW.顺便提一句。 911MB was the size of output made by auto-py-to-exe . 911MB 是auto-py-to-exe输出的大小。

I wonder how is it possible that no one yet has created a compressor that reads the code, checks what libraries are part of the code, then putting only them inside the compression.我想知道怎么可能还没有人创建一个压缩器来读取代码,检查哪些库是代码的一部分,然后只将它们放入压缩中。 In my case, auto-py-to-exe probably loaded all libraries that I ever installed.就我而言, auto-py-to-exe可能加载了我安装过的所有库。 That would explain the size of this compressed folder.这将解释这个压缩文件夹的大小。

Some suggest using https://virtualenv.pypa.io/en/stable/ but in my opinion, this library is very difficult, at least for me.有人建议使用https://virtualenv.pypa.io/en/stable/但在我看来,这个库非常困难,至少对我来说。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 pyinstaller 后如何修复 python 可执行文件的图标? - How can I fix icon of python executable after using pyinstaller? 如何在里面创建一个带可执行文件的可执行文件? - How can I create an executable with an executable inside? 减少 pyinstaller 可执行文件的大小 - Reduce pyinstaller executable size 如何在没有pyinstaller的情况下使用“ ./”创建python可执行文件 - How to create a python executable with “./” without pyinstaller 如何使用PyInstaller从PyCharm项目中创建可执行文件? - How do I create an executable file out of a PyCharm project using PyInstaller? 无法将tkinter与pyinstaller一起使用来创建脚本的可执行文件 - Can't create an executable of a script using tkinter with pyinstaller 如何将train_test_split导入pyinstaller可执行文件? - How can i import train_test_split to pyinstaller executable file? 如何将多个文件夹层次结构中的所有 python 文件导入单个 pyinstaller 可执行文件? - How can I import all my python files in multiple folder hierarchy into a single pyinstaller executable? 如何在由PyInstaller创建的可执行文件上使用xml.sax模块? - How can I use xml.sax module on an executable made with PyInstaller? Pyinstaller使用外部库创建可执行文件 - Pyinstaller create an executable with external libraries
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM