Installing pyinstaller on windows

pyinstaller 4.3

pip install pyinstaller Copy PIP instructions

Released: Apr 17, 2021

PyInstaller bundles a Python application and all its dependencies into a single package.

Statistics

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.6

Maintainers

Classifiers

  • Development Status
    • 6 — Mature
  • Environment
    • Console
  • Intended Audience
    • Developers
    • Other Audience
    • System Administrators
  • License
    • OSI Approved :: GNU General Public License v2 (GPLv2)
  • Natural Language
    • English
  • Operating System
    • MacOS :: MacOS X
    • Microsoft :: Windows
    • POSIX
    • POSIX :: AIX
    • POSIX :: BSD
    • POSIX :: Linux
    • POSIX :: SunOS/Solaris
  • Programming Language
    • C
    • Python
    • Python :: 3
    • Python :: 3 :: Only
    • Python :: 3.6
    • Python :: 3.7
    • Python :: 3.8
    • Python :: 3.9
    • Python :: Implementation :: CPython
  • Topic
    • 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.

Help keeping PyInstaller alive: Maintaining PyInstaller is a huge amount of work. PyInstaller development can only continue if users and companies provide sustainable funding. See http://www.pyinstaller.org/funding.html for how to support PyInstaller.

Documentation: https://pyinstaller.readthedocs.io/
Website: http://www.pyinstaller.org/
Code: https://github.com/pyinstaller/pyinstaller
Donate, Fund: http://www.pyinstaller.org/funding.html

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, Mac OS X, 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.6-3.9.
  • 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 OS X.
  • Bundles MS Visual C++ DLLs on Windows.

Installation

PyInstaller is available on PyPI. You can install it through pip :

Requirements and Tested Platforms

  • 3.6-3.9
  • tinyaes 1.0+ (only if using bytecode encryption). Instead of installing tinyaes, pip install pyinstaller[encryption] instead.
  • PyInstaller should work on Windows 7 or newer, but we only officially support Windows 8+.
  • We don’t support Python installed from the Windows store when not using virtual environments due to permission errors that can’t easily be fixed.
  • 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.

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.

  • AIX 6.1 or newer. PyInstaller will not work with statically linked Python libraries.
  • ldd

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.

Funding

Maintaining PyInstaller is a huge amount of work. PyInstaller development can only continue if users and companies provide sustainable funding. See http://www.pyinstaller.org/funding.html for how to support PyInstaller.

Changes in this Release

You can find a detailed list of changes in this release in the change log section of the manual.

Project details

Statistics

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

Как создать exe файл для Python кода с помощью PyInstaller

Установка PyInstaller

Установка PyInstaller не отличается от установки любой другой библиотеки Python.

Вот так можно проверить версию PyInstaller.

Я использую PyInstaller версии 4.2.

Создание exe файла с помощью PyInstaller

PyInstaller собирает в один пакет Python-приложение и все необходимые ему библиотеки следующим образом:

  1. Считывает файл скрипта.
  2. Анализирует код для выявления всех зависимостей, необходимых для работы.
  3. Создает файл spec, который содержит название скрипта, библиотеки-зависимости, любые файлы, включая те параметры, которые были переданы в команду PyInstaller.
  4. Собирает копии всех библиотек и файлов вместе с активным интерпретатором Python.
  5. Создает папку BUILD в папке со скриптом и записывает логи вместе с рабочими файлами в BUILD.
  6. Создает папку DIST в папке со скриптом, если она еще не существует.
  7. Записывает все необходимые файлы вместе со скриптом или в одну папку, или в один исполняемый файл.

Если использовать параметр команды onedir или -D при генерации исполняемого файла, тогда все будет помещено в одну папку. Это поведение по умолчанию. Если же использовать параметр onefile или -F , то все окажется в одном исполняемом файле.

Возьмем в качестве примера простейший скрипт на Python c названием simple.py, который содержит такой код.

Создадим один исполняемый файл. В командной строке введите:

После завершения установки будет две папки, BUILD и DIST, а также новый файл с расширением .spec. Spec-файл будет называться так же, как и файл скрипта.

Python создает каталог распространения, который содержит основной исполняемый файл, а также все динамические библиотеки.

Вот что произойдет после запуска файла.

Добавление файлов с данными, которые будут использоваться exe-файлом

Есть CSV-файл netflix_titles.csv, и Python-script, который считывает количество записей в нем. Теперь нужно добавить этот файл в бандл с исполняемым файлом. Файл Python-скрипта назовем просто simple1.py.

Создадим исполняемый файл с данными в папке.

Параметр —add-data позволяет добавить файлы с данными, которые нужно сохранить в одном бандле с исполняемым файлом. Этот параметр можно применить много раз.

Можно увидеть, что файл теперь добавляется в папку DIST вместе с исполняемым файлом.

Также, открыв spec-файл, можно увидеть раздел datas, в котором указывается, что файл netflix_titles.csv копируется в текущую директорию.

Запустим файл simple1.exe, появится консоль с выводом: Всего фильмов: 7787 .

Добавление файлов с данными и параметр onefile

Если задать параметр —onefile , то PyInstaller распаковывает все файлы в папку TEMP, выполняет скрипт и удаляет TEMP. Если вместе с add-data указать onefile, то нужно считать данные из папки. Путь папки меняется и похож на «_MEIxxxxxx-folder».

Скрипт обновлен для чтения папки TEMP и файлов с данными. Создадим exe-файл с помощью onefile и add-data.

После успешного создания файл simple1.exe появится в папке DIST.

Можно скопировать исполняемый файл на рабочий стол и запустить, чтобы убедиться, что нет никакой ошибки, связанной с отсутствием файла.

Дополнительные импорты с помощью Hidden Imports

Исполняемому файлу требуются все импорты, которые нужны Python-скрипту. Иногда PyInstaller может пропустить динамические импорты или импорты второго уровня, возвращая ошибку ImportError: No module named …

Для решения этой ошибки нужно передать название недостающей библиотеки в hidden-import.

Например, чтобы добавить библиотеку os, нужно написать вот так:

Файл spec

Файл spec — это первый файл, который PyInstaller создает, чтобы закодировать содержимое скрипта Python вместе с параметрами, переданными при запуске.

PyInstaller считывает содержимое файла для создания исполняемого файла, определяя все, что может понадобиться для него.

Файл с расширением .spec сохраняется по умолчанию в текущей директории.

Если у вас есть какое-либо из нижеперечисленных требований, то вы можете изменить файл спецификации:

  • Собрать в один бандл с исполняемым файлы данных.
  • Включить другие исполняемые файлы: .dll или .so.
  • С помощью библиотек собрать в один бандл несколько программы.

Например, есть скрипт simpleModel.py, который использует TensorFlow и выводит номер версии этой библиотеки.

Компилируем модель с помощью PyInstaller:

После успешной компиляции запускаем исполняемый файл, который возвращает следующую ошибку.

Исправим ее, обновив файл spec. Одно из решений — создать файл spec.

Команда pyi-makespec создает spec-файл по умолчанию, содержащий все параметры, которые можно указать в командной строке. Файл simpleModel.spec создается в текущей директории.

Поскольку был использован параметр —onefile , то внутри файла будет только раздел exe.

Если использовать параметр по умолчанию или onedir, то вместе с exe-разделом будет также и раздел collect.

Можно открыть simpleModel.spec и добавить следующий текст для создания хуков.

Создаем хуки и добавляем их в hidden imports и раздел данных.

Файлы хуков расширяют возможность PyInstaller обрабатывать такие требования, как необходимость включать дополнительные данные или импортировать динамические библиотеки.

Обычно пакеты Python используют нормальные методы для импорта своих зависимостей, но в отдельных случаях, как например TensorFlow, существует необходимость импорта динамических библиотек. PyInstaller не может найти все библиотеки, или же их может быть слишком много. В таком случае рекомендуется использовать вспомогательный инструмент для импорта из PyInstaller.utils.hooks и собрать все подмодули для библиотеки.

Скомпилируем модель после обновления файла simpleModel.spec.

Скопируем исполняемый файл на рабочий стол и увидим, что теперь он корректно отображает версию TensorFlow.

Вывод:

PyInstaller предлагает несколько вариантов создания простых и сложных исполняемых файлов из Python-скриптов:

  • Исполняемый файл может собрать в один бандл все требуемые данные с помощью параметра —add-data .
  • Исполняемый файл и зависимые данные с библиотеками можно собрать в один файл или папку с помощью —onefile или —onedir соответственно.
  • Динамические импорты и библиотеки второго уровня можно включить с помощью hidden-imports .
  • Файл spec позволяет создать исполняемый файл для обработки скрытых импортов и других файлов данных с помощью хуков.

Подписывайтесь на канал в Дзене

Полезный контент для начинающих и опытных программистов в канале Лента Python разработчика — Как успевать больше, делать лучше и не потерять мотивацию.

Читайте также:  Изменить монитор по умолчанию windows 10
Оцените статью