PyInstaller. Дистрибуция кода Python
PyInstaller — обычный пакет python. Он может быть установлен с использованием pip:
pip install pyinstaller
Установка в Windows:
Для Windows установка pywin32 или pypiwin32 — обязательное условие. Когда pyinstaller устанавливается с помощью pip, то pypiwin32 устанавливается автоматически.
Установка в Mac OS X:
PyInstaller работает с Python 2.7 по умолчанию в текущей Mac OS X. Однако, если вы планируете использовать более позднюю версию Python или если вы используете какой-либо из основных пакетов, таких как PyQt, Numpy, Matplotlib, Scipy и т. п. Мы настоятельно рекомендуем установить их с помощью MacPorts, либо Homebrew.
Установка из архива:
Если установка c помощью pip недоступна, загрузите сжатый архив из PyPI .
Чтобы протестировать версию, которая находится на стадии разработки, вы можете загрузить сжатый архив из раздела разработки страницы загрузки PyInstaller.
Распакуйте архив и найдите скрипт setup.py .Выполните python setup.py install с правами администратора для установки или обновления PyInstaller.
Проверка установки
Команда pyinstaller должна присутствовать в системном пути для всех платформ после успешной установки.
Это можно проверить, набрав в командной строке.
Использование Pyinstaller
Перейдите к каталогу, в котором находится ваш файл и введите:
pyinstaller myfile.py
Pyinstaller анализирует файл и создает:
Файл myfile.spec в том же каталоге, что и myfile.py
Папку сборки в том же каталоге, что и myfile.py
Папку dist в том же каталоге, что и myfile.py
Файлы журналов в папке сборки
Само приложение можно будет найти вложенным в папку dist
Объединение в одну папку
Если PyInstaller запускается без каких-либо параметров для myscript.py, то по умолчанию на выход получаем одну папку (с именем myscript). Она содержит файл с именем myscript (myscript.exe в Windows) вместе со всеми необходимыми зависимостями.
Приложение можно пересылать, сжав папку в zip-файл.
Режим «One Folder» можно установить с помощью опции -D или —onedir
pyinstaller myscript.py -D
Преимущества:
Одно из основных преимуществ упаковки в папку — легче отлаживать проблемы. Если какие-либо модули не импортируются, их можно проверить в папке.
Если в коде несколько изменений, но используемые зависимости точно совпадают, дистрибуторы могут просто отправить один исполняемый файл (который обычно меньше всей папки).
Недостатки:
Единственный недостаток этого метода — пользователи должны искать исполняемый файл в большом количестве файлов.
Также пользователи могут удалять/изменять другие файлы — это может привести к неправильной работе приложения.
Объединение в один файл
pyinstaller myscript.py -F
Флаг -F или —onefile определяет, что все будет упаковано в единый исполняемый файл myscript.exe .
Одиночный файл будет работать медленнее, чем при упаковке в папку. Также одиночные файлы сложнее отлаживать.
Синтаксис
pyinstaller [options] script [script . ] | specfile
Примечания
PyInstaller собирает python-приложение и все зависимости в один пакет. Пользователь может запускать приложение без установки интерпретатора python или каких-либо модулей. Pyinstaller поддерживает python 2.7 и python 3.3+ и такие библиотеки как: numpy, Django, OpenCv и другие.
Важные моменты, о которых следует помнить:
Pyinstaller поддерживает Python 2.7 и Python 3.3+
Pyinstaller был протестирован на Windows, Linux и Mac OS X.
Pyinstaller НЕ поддерживает кросс компиляцию из одной платформы для всех возможных (т.е. вы не можете создать исполняемый файл для одной операционной системы из другой операционной системы)
How to Install PyInstaller¶
PyInstaller is available as a regular Python package. The source archives for released versions are available from PyPi, but it is easier to install the latest version using pip:
pip install pyinstaller
To upgrade existing PyInstaller installation to the latest version, use:
pip install --upgrade pyinstaller
To install the current development version, use:
pip install https://github.com/pyinstaller/pyinstaller/tarball/develop
To install directly using pip’s built-in git checkout support, use:
pip install git+https://github.com/pyinstaller/pyinstaller
or to install specific branch (e.g., develop ):
pip install git+https://github.com/pyinstaller/pyinstaller@develop
Installing from the source archive¶
The source code archive for released versions of PyInstaller are available at PyPI and on PyInstaller Downloads page.
Even though the source archive provides the setup.py script, installation via python setup.py install has been deprecated and should not be used anymore. Instead, run pip install . from the unpacked source directory, as described below.
- Unpack the source archive.
- Move into the unpacked source directory.
- Run pip install . from the unpacked source directory. If installing into system-wide python installation, administrator privilege is required.
The same procedure applies to installing from manual git checkout:
git clone https://github.com/pyinstaller/pyinstaller cd pyinstaller pip install .
If you intend to make changes to the source code and want them to take effect immediately, without re-installing the package each time, you can install it in editable mode:
pip install -e .
For platforms other than Windows, GNU/Linux and macOS, you must first build the bootloader for your platform: see Building the Bootloader . After the bootloader has been built, use the pip install . command to complete the installation.
Verifying the installation¶
On all platforms, the command pyinstaller should now exist on the execution path. To verify this, enter the command:
pyinstaller --version
The result should resemble 4.n for a released version, and 4.n.dev0-xxxxxx for a development branch.
If the command is not found, make sure the execution path includes the proper directory:
- Windows: C:\PythonXY\Scripts where XY stands for the major and minor Python version number, for example C:\Python38\Scripts for Python 3.8)
- GNU/Linux: /usr/bin/
- macOS (using the default Apple-supplied Python) /usr/bin
- macOS (using Python installed by homebrew) /usr/local/bin
- macOS (using Python installed by macports) /opt/local/bin
To display the current path in Windows the command is echo %path% and in other systems, echo $PATH .
If you cannot use the pyinstaller command due to the scripts directory not being in PATH , you can instead invoke the PyInstaller module, by running python -m PyInstaller (pay attention to the module name, which is case sensitive). This form of invocation is also useful when you have PyInstaller installed in multiple python environments, and you cannot be sure from which installation the pyinstaller command will be ran.
Installed commands¶
The complete installation places these commands on the execution path:
- pyinstaller is the main command to build a bundled application. See Using PyInstaller .
- pyi-makespec is used to create a spec file. See Using Spec Files .
- pyi-archive_viewer is used to inspect a bundled application. See Inspecting Archives .
- pyi-bindepend is used to display dependencies of an executable. See Inspecting Executables .
- pyi-grab_version is used to extract a version resource from a Windows executable. See Capturing Windows Version Data .
- pyi-set_version can be used to apply previously-extracted version resource to an existing Windows executable.
© Copyright This document has been placed in the public domain.. Revision 362ff1b9 .
Установим 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 —onefile MyFile.py
Не могу установить pyinstaller. Что делать?
Только начал изучать Python и столкнулся с такой проблемой, когда хотел преобразовать файл в формат .exe
Просто не получается установить pyinstaller через cmd, выдаёт ошибку. Подробнее на прикреплённом скриншоте. Заранее спасибо.
- Вопрос задан более двух лет назад
- 506 просмотров
4 комментария
Простой 4 комментария