Собираем проект на python3&PyQT5 под Windows, используя PyInstaller
Причиной написания статьи, явилось огромное количество постоянно возникающих у новичков вопросов такого содержания: «Как собрать проект c pyqt5», «Почему не работает», «Какой инструмент выбрать» и т.д. Сегодня научимся собирать проекты без мучений и танцев с бубном.
Как-то пришлось написать небольшое desktop-приложение. В качестве языка программирования для разработки был выбран python, поскольку для решения моей задачи он подходил идеально. В стандартную библиотеку Python уже входит библиотека tkinter, позволяющая создавать GUI. Но проблема tkinter в том, что данной библиотеке посвящено мало внимания, и найти в интернете курс, книгу или FAQ по ней довольно-таки сложно. Поэтому было решено использовать более мощную, современную и функциональную библиотеку Qt, которая имеет привязки к языку программирования python в виде библиотеки PyQT5. Более подробно про PyQT можете почитать здесь. В качестве примера я буду использовать код:
Если вы более-менее опытный разработчик, то понимаете, что без интерпретатора код на python не запустить. А хотелось бы дать возможность каждому пользователю использовать программу. Вот здесь к нам на помощь и приходят специальные библиотеки позволяющие собирать проекты в .exe, которые можно потом без проблем запустить, как обычное приложение.
Существует большое количество библиотек, позволяющих это сделать, среди которых самые популярные: cx_Freeze, py2exe, nuitka, PyInstaller и др. Про каждую написано довольно много. Но надо сказать, что многие из этих решений позволяют запускать код только на компьютере, с предустановленным интерпретатором и pyqt5. Не думаю, что пользователь будет заморачиваться и ставить себе дополнительные пакеты и программы. Надеюсь, вы понимаете, что запуск программы на dev-среде и у пользователя это не одно и тоже. Также нужно отметить, что у каждого решения были свои проблемы: один не запускался, другой собирал то, что не смог потом запустить, третий вообще отказывался что-либо делать.
После долгих танцев с бубном и активным гуглением, мне все же удалось собрать проект с помощью pyinstaller, в полностью работоспособное приложение.
Немного о Pyinstaller
Pyinstaller собирает python-приложение и все зависимости в один пакет. Пользователь может запускать приложение без установки интерпретатора python или каких-либо модулей. Pyinstaller поддерживает python 2.7 и python 3.3+ и такие библиотеки как: numpy, PyQt, Django, wxPython и другие.
Pyinstaller тестировался на Windows, Mac OS X и Linux. Как бы там ни было, это не кросс-платформенный компилятор: чтобы сделать приложение под Windows, делай это на Windows; Чтобы сделать приложение под Linux, делай это на Linux и т.д.
PyInstaller успешно используется с AIX, Solaris и FreeBSD, но тестирование не проводилось.
Подробнее о PyInstaller можно почитать здесь: документация.
К тому же после сборки приложение весило всего около 15 мб. Это к слову и является преимуществом pyinstaller, поскольку он не собирает все подряд, а только необходимое. Аналогичные же библиотеки выдавали результат за 200-300 мб.
Приступаем к сборке
Прежде чем приступить к сборке мы должны установить необходимые библиотеки, а именно pywin32 и собственно pyinstaller:
Чтобы убедится, что все нормально установилось, вводим команду:
должна высветиться версия pyinstaller. Если все правильно установилось, идем дальше.
В папке с проектом запускаем cmd и набираем:
Собственно это и есть простейшая команда, которая соберет наш проект.
Синтаксис команды pyinstaller таков:
pyinstaller [options] script [script . ] | specfile
Наиболее часто используемые опции:
—onefile — сборка в один файл, т.е. файлы .dll не пишутся.
—windowed -при запуске приложения, будет появляться консоль.
—noconsole — при запуске приложения, консоль появляться не будет.
—icon=app.ico — добавляем иконку в окно.
—paths — возможность вручную прописать путь к необходимым файлам, если pyinstaller
не может их найти(например: —paths D:\python35\Lib\site-packages\PyQt5\Qt\bin)
PyInstaller анализирует файл myscript.py и делает следующее:
- Пишет файл myscript.spec в той же папке, где находится скрипт.
- Создает папку build в той же папке, где находится скрипт.
- Записывает некоторые логи и рабочие файлы в папку build.
- Создает папку dist в той же папке, где находится скрипт.
- Пишет исполняемый файл в папку dist.
В итоге наша команда будет выглядеть так:
После работы программы вы найдете две папки: dist и build. Собственно в папке dist и находится наше приложение. Впоследствии папку build можно спокойно удалить, она не влияет на работоспособность приложения.
Установим pyinstaller под Windows 10 (python 3.5)
Итак, как пользоваться pyinstaller, я расскажу ниже, но сначала его надо установить.
Для начала идем сюда https://pypi.python.org/pypi/pypiwin32/219 и качаем под нужную систему.
Это расширения Python для Windows нужен для работы c WinAPI и создания COM-ов. В данный момент для меня был pypiwin32-219-cp35-none-win32.whl я писал на Python 3.5 и компилить будем под Win10.
Далее просто в командной строке
pip install <путь к файлу>\ pypiwin32-219-cp35-none-win32.whl
Тут команда разработчиков советует сделать виртуальное окружение и устанавливать pyinstaller в него, но можно и без этого. Опускаем этот момент и…
pip install PyInstaller
Далее, чтобы сделать свой exe файл сделаем папку, где все это будет компилиться. Ложим туда свой крутой py-файл, создаем директории Build и Dist. В папке Dist найдете свой exe файл, но после команды:
pyinstaller 5.1
PyInstaller bundles a Python application and all its dependencies into a single package.
Navigation
Project links
- Homepage
- Source
Statistics
- Stars:
- Forks:
- Open issues/PRs:
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: GNU General Public License v2 (GPLv2) (GPLv2-or-later with a special exception which allows to use PyInstaller to build and distribute non-free programs (including commercial ones))
Author: Hartmut Goebel, Giovanni Bajo, David Vierra, David Cortesi, Martin Zibricky
Tags packaging, app, apps, bundle, convert, standalone, executable, pyinstaller, cxfreeze, freeze, py2exe, py2app, bbfreeze
Requires: Python <3.11, >=3.7
Maintainers
Classifiers
- Development Status
- 6 — Mature
- Console
- Developers
- Other Audience
- System Administrators
- OSI Approved :: GNU General Public License v2 (GPLv2)
- English
- MacOS :: MacOS X
- Microsoft :: Windows
- POSIX
- POSIX :: AIX
- POSIX :: BSD
- POSIX :: Linux
- POSIX :: SunOS/Solaris
- C
- Python
- Python :: 3
- Python :: 3 :: Only
- Python :: 3.7
- Python :: 3.8
- Python :: 3.9
- Python :: 3.10
- Python :: Implementation :: CPython
- Software Development
- Software Development :: Build Tools
- Software Development :: Interpreters
- Software Development :: Libraries :: Python Modules
- System :: Installation/Setup
- System :: Software Distribution
- Utilities
Project description
PyInstaller bundles a Python application and all its dependencies into a single package. The user can run the packaged app without installing a Python interpreter or any modules.
Documentation: https://pyinstaller.readthedocs.io/ Website: http://www.pyinstaller.org/ Code: https://github.com/pyinstaller/pyinstaller PyInstaller reads a Python script written by you. It analyzes your code to discover every other module and library your script needs in order to execute. Then it collects copies of all those files – including the active Python interpreter! – and puts them with your script in a single folder, or optionally in a single executable file.
PyInstaller is tested against Windows, macOS, and GNU/Linux. However, it is not a cross-compiler: to make a Windows app you run PyInstaller in Windows; to make a GNU/Linux app you run it in GNU/Linux, etc. PyInstaller has been used successfully with AIX, Solaris, FreeBSD and OpenBSD, but is not tested against them as part of the continuous integration tests.
Main Advantages
- Works out-of-the-box with any Python version 3.7-3.10.
- Fully multi-platform, and uses the OS support to load the dynamic libraries, thus ensuring full compatibility.
- Correctly bundles the major Python packages such as numpy, PyQt5, PySide2, Django, wxPython, matplotlib and others out-of-the-box.
- Compatible with many 3rd-party packages out-of-the-box. (All the required tricks to make external packages work are already integrated.)
- Libraries like PyQt5, PySide2, wxPython, matplotlib or Django are fully supported, without having to handle plugins or external data files manually.
- Works with code signing on macOS.
- Bundles MS Visual C++ DLLs on Windows.
Installation
PyInstaller is available on PyPI. You can install it through pip :
Requirements and Tested Platforms
- Python:
- 3.7-3.10 1.0+ (only if using bytecode encryption). Instead of installing tinyaes, pip install pyinstaller[encryption] instead.
- Windows (32bit/64bit):
- PyInstaller should work on Windows 7 or newer, but we only officially support Windows 8+.
- Support for Python installed from the Windows store without using virtual environments requires PyInstaller 4.4 or later.
- GNU/Linux (32bit/64bit)
- ldd: Console application to print the shared libraries required by each program or shared library. This typically can be found in the distribution-package glibc or libc-bin .
- objdump: Console application to display information from object files. This typically can be found in the distribution-package binutils .
- objcopy: Console application to copy and translate object files. This typically can be found in the distribution-package binutils , too.
- macOS (64bit):
- macOS 10.15 (Catalina) or newer.
Usage
Basic usage is very simple, just run it against your main script:
For more details, see the manual.
Untested Platforms
The following platforms have been contributed and any feedback or enhancements on these are welcome.
- FreeBSD
- Solaris
- ldd
- objdump
- AIX 6.1 or newer. PyInstaller will not work with statically linked Python libraries.
- ldd
- PowerPC GNU/Linux (Debian)
Before using any contributed platform, you need to build the PyInstaller bootloader, as we do not ship binary packages. Download PyInstaller source, and build the bootloader:
Then install PyInstaller:
or simply use it directly from the source (pyinstaller.py).
Support
See http://www.pyinstaller.org/support.html for how to find help as well as for commercial support.
Changes in this Release
You can find a detailed list of changes in this release in the Changelog section of the manual.
Project details
Project links
- Homepage
- Source
Statistics
- Stars:
- Forks:
- Open issues/PRs:
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: GNU General Public License v2 (GPLv2) (GPLv2-or-later with a special exception which allows to use PyInstaller to build and distribute non-free programs (including commercial ones))
Author: Hartmut Goebel, Giovanni Bajo, David Vierra, David Cortesi, Martin Zibricky
Tags packaging, app, apps, bundle, convert, standalone, executable, pyinstaller, cxfreeze, freeze, py2exe, py2app, bbfreeze