Reduce the size of your Pyinstaller EXE
report this ad
report this ad
report this ad
In this Python Pyinstaller tutorial, we will show you several methods you can use to reduce the size of your Pyinstaller EXE.
How to reduce Pyinstaller EXE size?
- Using UPX
- Virtual Environments
- Optimizing your Code and Imports
Using UPX
Using the UPX packer is an easy and effective way of reducing the size of your Pyinstaller EXE by about 20 – 50% (varies based on the Code and Libraries used).
All you have to do is go to the UPX website, and download the appropriate folder. No need to install anything, just unzip it anywhere on your device.
Now if you are on windows, you should note down the filepath of the UPX folder, and add it to your Environment Variables (PATH). Pyinstaller will automatically detect and use UPX if you have it added to PATH.
For those of you who do not want (or cannot) to add it to PATH, you can also add it directly into the pyinstaller command using the following option:
Note: Do not make the silly mistake of including the EXE in the filepath. You need to include the filepath to the UPX folder, not the EXE inside it.
Virtual Environments
Although UPX is the most easiest way to reduce the size of your Pyinstaller EXE, using a Virtual Environment is actually the most effective, and most recommended.
How does this work exactly?
Well, a Virtual environment is basically like a fresh Python installation, with no libraries installed. Why is this beneficial though?,
The problem that most people face, is that many “extra” or “un-needed” libraries end up inside their EXE’s. For example, when I was creating a “Tkinter” (a GUI library) application, “PyQt6” (another GUI library) was also included, even though I was not using PyQt6 inside my application. (I had PyQt6 installed on my device)
This is pretty common, and happens in Pyinstaller and other similar EXE converting libraries.
To resolve this, we use Virtual Environments and only install the required libraries that we know we will be using. This ensures that Pyinstaller will not “accidentally” include any other libraries (because there will no extra libraries installed in the Virtual environment).
Unfortunately, the explanation required to explain Virtual Environments and how to set it up, is a bit lengthy. Hence, we have a created a separated dedicated tutorial to show you how to do so. We have used a sample Pyinstaller application there, and also shown the “before” and “after” sizes.
Optimizing your Code and Imports
This is a bit of an extension, as to what we discussed in the Virtual Environments section. While Virtual environments will ensure only the libraries that you explicitly import are imported, you should double-check to make sure all of the libraries you are importing are actually needed.
Are you making some imports that you never actually use? Remove them!
You can also try and evaluate whether you can possibly remove some libraries you are using. If you are only using a single function, or single feature from that library, this will cause the whole library to be imported.
- Try making a custom implementation of that feature
- Find a smaller library that offers that feature.
- Find an existing library that you are already using, which may offer the same (or similar) feature.
Other than this, you should work on optimizing and reducing redundant code. The smaller your code files are, the smaller your EXE will be. The gains from this will obviously be rather minimal, so don’t expect a drastic difference.
This marks the end of the “Reduce the size of your Pyinstaller EXE” Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

report this ad
Reducing size of pyinstaller exe
I have a simple pandas pyinstaller exe which is over 40MB.
40MB+ for this seems a bit overkill.
How can I reduce this as much as possible?
This however is not practical considering how big the exclusion list would be.
How do I select a folder for pyinstaller to get modules from and exclude everything else so I may have a small application?
It’s also worth mentioning. By default, Pyinstaller does not detect pandas.
A possible solution when using multiple executables, could be to link each executable to a separate folder or executable with all imports.
5 Answers 5
try setting up your environment with a virtualenv, and install in there only the required libraries
some details on working with virtual env are here: https://virtualenv.pypa.io/en/stable/
For me, it is a simple case of using pandas that the exe is huge.
Though removing certain directories was helpful, as was UPXING that helped a great deal also.
I got it reduced a lot and it was not doing this by default.
That being said, the final and most import solution is talked about here: Importing Python modules from a select location . So there was a feature that did all this, but for now there is some manual handling involved because: multipackage-bundles is broken.
Now to the simple solution for lots of exe’s
If you have many executables, I highly recommend this approach:
Now put abd.exe in the one directory of abc.py folder as well as any other external scripts. Be sure they are differently named or only one script will run.
This works really well because all the dependencies are in one folder. This is how it should be. So in this example say you had a 40mb one folder. For each additional exe afterwards, it will only be +5mb(or how big the exe is) rather than 40mb each.
![]()
The python interpreter and all imported modules are included in the executable.
You can try adding modules you want to exclude to the excludes list under Analysis in your spec file.
You could also try compressing the executable using UPX. See A note on using UPX
![]()
I had a similar problem and found a solution. I used Windows terminal preview. 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).
Inside Windows Power Shell in Windows terminal preview I installed all the necessary libraries, then I opened the path to my file and tried to use this command:
pyinstaller —onefile -w ‘filename.py’
. but, the output exe didn’t work. 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. The command used by this GUI is:
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 .
BTW. 911MB was the size of output made by 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. That would explain the size of this compressed folder.
Уменьшить размер исполняемого файла pyinstaller
У меня есть только одна строка кода input() , написанная на python и заполненная pyinstaller с опцией —onefile . Размер исполняемого файла 4577 КБ, что почти 5 МБ. Как я могу уменьшить его размер или исключить некоторые автоматически связанные библиотеки?
2 ответа
Файл .exe, который вы создаете с помощью pyinstaller, включает в себя интерпретатор python и все модули, включенные в ваш скрипт. Возможно, используемые вами модули имеют большую библиотеку. Однако вы можете попробовать использовать py2exe , но это может не сработать для всех проектов. Другой способ уменьшить его — это использовать программу сжатия, например, сжать исполняемый файл с помощью UPX (посмотрите на это: http://htmlpreview.github.io/?https://github.com/pyinstaller/pyinstaller/blob/v2.0/doc/Manual.html#a-note-on-using- UPX ) . Вы также можете попробовать исключить некоторые элементы, но на усмотрение, что удаление таких элементов не влияет на функциональность вашего .exe.
Ах, вы не создаете сборку в отдельной виртуальной среде.
Создайте виртуальную среду только для целей сборки и установите необходимые пакеты в этой среде.
В вашем cmd выполните их для создания виртуальной среды
python -m venv build_env
cd build_env
C: \ build_env \ Scripts \ Activate
Вы увидите это >> (build_env) C: \ build_env
Установите все пакеты, которые вам нужны для вашего скрипта, начните с pyinstaller
Уменьшить размер исполняемого файла pyinstaller
У меня есть только одна строка кода input() написанный на python и упакованный с pyinstaller с опцией —onefile , Размер исполняемого файла 4577 КБ, что почти 5 МБ. Как я могу уменьшить его размер или исключить некоторые автоматически связанные библиотеки?
3 ответа
Файл.exe, который вы создаете с помощью pyinstaller, включает в себя интерпретатор python и все модули, включенные в ваш скрипт. Возможно, используемые вами модули имеют большую библиотеку. Однако вы можете попробовать использовать py2exe, но это может не сработать для всех проектов. Другой способ уменьшить его — использовать программу сжатия, например, сжать исполняемый файл с помощью UPX (посмотрите на это: http://htmlpreview.github.io/?https://github.com/pyinstaller/pyinstaller/blob/v2.0/doc/Manual.html). Вы также можете попробовать исключить некоторые элементы, но по усмотрению, удаление таких элементов не влияет на функциональность вашего.exe.
Ах, вы не создаете сборку в отдельной виртуальной среде.
Создайте виртуальную среду только для целей сборки и установите необходимые пакеты в этой среде.
в вашем cmd выполните их, чтобы создать виртуальную среду
python -m venv build_env
cd build_env
C: \ build_env \ Scripts \ Активировать
вы увидите это >>(build_env) C:\build_env
Установите все пакеты, которые вам нужны для вашего скрипта, начните с pyinstaller
Как только вы все установили, соберите exe-файл, как и раньше. Exe, созданный с использованием виртуальной среды, будет быстрее и меньше по размеру! Для более подробной информации проверьте https://python-forum.io/Thread-pyinstaller-exe-size
У меня была аналогичная проблема, и я нашел решение. Я использовал предварительный просмотр терминала Windows. Эта программа позволяет создавать различные виртуальные среды, такие как Windows Power Shell (кстати, Linux Ubuntu тоже. Также стоит отметить: вы можете установить много терминалов в этой программе и даже открыть несколько одновременно. Очень крутая штука).
Внутри Windows Power Shell в предварительном просмотре терминала Windows я установил все необходимые библиотеки (например, pandas и т. Д.), Затем я открыл путь к моему файлу и попытался использовать эту команду:
. но вывод exe не сработало. Почему-то в консоли говорилось, что не хватает одной библиотеки (которую я установил ранее). Я нашел решение в имитации библиотеки. В этом графическом интерфейсе используется следующая команда:
И этот хорошо работает. Я уменьшил размер моей выходной exe-программы с 911 МБ до 82,9 МБ .
Кстати: 911 МБ — это размер выходного файла.
Интересно, как это возможно, что никто еще не создал компрессор, который читает код, проверяет, какие библиотеки являются частью кода, а затем помещает только их в сжатие. В моем случае, auto-py-to-exe наверное, загрузил все библиотеки, которые я когда-либо устанавливал. Это объяснило бы размер этой сжатой папки.