Pip install pyinstaller windows

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:

Note

PyInstaller is split into two packages pyinstaller and
pyinstaller-hooks-contrib. These should be kept approximately (roughly
within a year of each other) in sync. To that end, if you choose to pin your
pyinstaller version, please also pin pyinstaller-hooks-contrib. If
you upgrade pyinstaller, you will also need to upgrade
pyinstaller-hooks-contrib.

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.

Note

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.

The installation procedure is:
  1. Unpack the source archive.

  2. Move into the unpacked source directory.

  3. 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:

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.

Troubleshooting missing PyInstaller command

In a properly setup Python environment, the command pyinstaller should now
exist on the execution path and the command below should display PyInstaller’s
version.

If the command is not found, make sure that the PATH (the executable search
path) environment variable includes the directory that the pyinstaller
executable was installed into.

  • On Windows, this location is either of the paths returned by:

    import sysconfig; print(sysconfig.get_path("scripts"))
    import site; print(site.USER_BASE + "\\Scripts")
    
  • On UNIX, this location is either of the paths returned by:

    import sysconfig; print(sysconfig.get_path("scripts"))
    import site; print(site.USER_BASE + "/bin")
    

To display the current path in Windows the command is echo %PATH% and on
other systems, echo $PATH.

Note

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.

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.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.8-3.13.

  • 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, PyQt6, PySide6, 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.)

  • 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:

pip install pyinstaller

Requirements and Tested Platforms

  • Python:
    • 3.8-3.13. Note that Python 3.10.0 contains a bug making it unsupportable by
      PyInstaller. PyInstaller will also not work with beta releases of Python
      3.14.

  • Windows (32bit/64bit/ARM64):
    • 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.

  • Linux:
    • GNU libc based distributions on architectures x86_64, aarch64,
      i686, ppc64le, s390x.

    • musl libc based distributions on architectures x86_64, aarch64.

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

    • Raspberry Pi users on armv5armv7 should add piwheels as an extra
      index url then pip install pyinstaller
      as usual.

  • macOS (x86_64 or arm64):
    • macOS 10.15 (Catalina) or newer.

    • Supports building universal2 applications provided that your installation
      of Python and all your dependencies are also compiled universal2.

Usage

Basic usage is very simple, just run it against your main script:

pyinstaller /path/to/yourscript.py

For more details, see the manual.

Untested Platforms

The following platforms have been contributed and any feedback or
enhancements on these are welcome.

  • FreeBSD
    • ldd

  • Solaris
    • ldd

    • objdump

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

    • ldd

  • Linux on any other libc implementation/architecture combination not listed
    above.

Before using any contributed platform, you need to build the PyInstaller
bootloader. This will happen automatically when you pip install pyinstaller
provided that you have an appropriate C compiler (typically
either gcc or clang) and zlib’s development headers already installed.

Support

  • Official debugging guide: https://pyinstaller.org/en/v6.13.0/when-things-go-wrong.html

  • Assorted user contributed help topics: https://github.com/pyinstaller/pyinstaller/wiki

  • Web based Q&A forums: https://github.com/pyinstaller/pyinstaller/discussions

  • Email based Q&A forums: https://groups.google.com/g/pyinstaller

Changes in this Release

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

C помощью Python можно автоматизировать многие задачи — достаточно написать скрипт и запустить его на терминале. Python — самый быстрый и простой язык сценариев. Если вы не хотите каждый день открывать терминал и запускать одну и ту же команду, можно создать исполняемый файл. Создать exe-файл в Python можно с помощью PyInstaller и других библиотек.

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

PyInstaller — популярный инструмент для преобразования скриптов Python в автономные исполняемые файлы (.exe) в Windows.

Установка PyInstaller 

PyInstaller доступен в виде обычного пакета Python. Архивы с исходными текстами для выпущенных версий доступны в PyPI, но инструмент проще установить с помощью pip:

C:\> pip install pyinstaller

Это поможет обновить PyInstaller до последней версии:

C:\> pip install —upgrade pyinstaller

Установка текущей версии разработки:

C:\> pip install https://github.com/pyinstaller/pyinstaller/tarball/

Алгоритм действия 

В качестве примера возьмем один файл на Python, чтобы подробно объяснить этапы упаковки. Рассмотрим Python 3.11.0 после установки aspose.cells.

1.Создайте файл с именем example.py: 

import os

from jpype import *

__cells_jar_dir__ = os.path.dirname(__file__)

addClassPath(os.path.join(__cells_jar_dir__, "aspose-cells-23.1.jar"))

addClassPath(os.path.join(__cells_jar_dir__, "bcprov-jdk15on-160.jar"))

addClassPath(os.path.join(__cells_jar_dir__, "bcpkix-jdk15on-1.60.jar"))

addClassPath(os.path.join(__cells_jar_dir__, "JavaClassBridge.jar"))

import jpype

import asposecells

jpype.startJVM()

from asposecells.api import Workbook, FileFormatType, CellsHelper

print(CellsHelper.getVersion())

workbook = Workbook(FileFormatType.XLSX)

workbook.getWorksheets().get(0).getCells().get("A1").putValue("Hello World")

workbook.save("output.xlsx")

jpype.shutdownJVM()

py

2.Создайте папку c:\app и копию example.py c:\app.

3. Откройте командную строку и выполните команду example.py pyinstaller 

C:\app> pyinstaller example.py

4. Скопируйте файлы jar(aspose-cells-xxx.jar, bcprov-jdk15on-160.jar, bcpkix-jdk15on-1.60.jar, JavaClassBridge.jar. Они находятся в папке C:\Python311\Lib\site-packages\asposecells\lib) в c:\app.

5. Отредактируйте файл с суффиксом spec, чтобы добавить раздел данных, подобный example.spec.

6. Запустите pyinstaller example.spec в окне командной строки.

C:\app> pyinstaller example.spec

7. Переключите каталог на C:\app\dist\example, и вы найдете файл example.exe.

Создание exe-файла с помощью библиотеки auto-py-to-exe 

С помощью auto-py-to-exe, проекта Брента Воллебрегта можно создавать собственные исполняемые приложения на Python. Под графическим интерфейсом находится PyInstaller, приложение на базе терминала для создания исполняемых файлов на Python для Windows, Mac и Linux. 

Установка auto-py-to-exe 

  1. Откройте командную строку, выполнив поиск CMD.
  2. Используйте pip-менеджер пакетов Python для установки auto-py-to-exe:

pip install auto-py-to-exe

Алгоритм действия 

  1. Откройте командную строку, выполнив поиск CMD.
  2. Запустите auto-py-to-exe из командной строки.
  3. Нажмите на кнопку Browse и перейдите к нашему примеру файла на Python.
  4. Настройте приложение на использование одного файла. Это позволит объединить приложение и поддерживающие его библиотеки Python в один исполняемый файл.
  5. Настройте приложение на консольное управление. Так можно увидеть все ошибки, выводимые в командную строку. Как только мы будем уверены, что приложение работает правильно, можно настроить его на оконное управление.
  6. Нажмите на раскрывающийся список параметров и выберите значок для вашего приложения. Это необязательный шаг, но он повышает качество приложения. 
  7. Нажмите «Дополнительно», ‎в поле «Имя» ‎введите название вашего приложения. Например, «Программа запуска приложений».
  8. Прокрутите страницу вниз и нажмите «Преобразовать. PY в .EXE»‎, чтобы начать процесс. Это займет пару минут.
  9. Нажмите на кнопку Open Output Folder, чтобы открыть папку, содержащую приложение.
  10. Дважды щелкните по значку, чтобы запустить приложение.

Создание exe-файла с помощью библиотеки cx_Freeze 

Преобразовать скрипт Python в автономный исполняемый файл (.exe) можно и с помощью «cx_Freeze».

Установка cx_Freeze 

Установить его легко с помощью pip:

Алгоритм действия 

Создайте установочный скрипт (например, «setup.py») в том же каталоге, что и ваш скрипт на Python. Этот скрипт предоставит конфигурацию для «cx_Freeze». Простой пример проекта:

from cx_Freeze import setup, Executable

   setup(

       name="YourAppName",

       version="1.0",

       description="Your application description",

       executables=[Executable("your_script.py")],

   )   

py

Замените «YourAppName» и «Your application description» на название и описание вашего приложения, а «your_script.py» — на название вашего скрипта на Python.

Откройте терминал, перейдите в каталог, содержащий ваш скрипт на Python и файл «setup.py»:

python setup.py build

Это создаст каталог «build», содержащий исполняемый файл.

После выполнения команды «build» вы можете найти исполняемый файл в каталоге `build`. Он будет находиться в подкаталоге с названием вашей операционной системы (например, «build\exe.win-amd64-3.8» для 64-разрядного исполняемого файла Windows).

Теперь у вас должен быть отдельный исполняемый файл, который вы можете распространять и запускать на компьютере без установленного Python. Помните, что если у вашего скрипта есть внешние зависимости, то может потребоваться включить их в сценарий «setup.py». 

Создание exe-файла с помощью библиотеки py2exe 

Преобразование интерпретируемого языкового кода в исполняемый файл еще называют замораживанием. Для этого можно использовать модуль py2exe.

Установка py2exe 

Чтобы использовать модуль py2exe, нужно его установить. Сделаем это с помощью pip:

Алгоритм действия 

Напишем программу, которая будет выводить текст на консоль:

import math

print("Hannibal ante Portas")

print(factorial(4))

py

Запустим следующие команды в командной строке Windows, чтобы создать каталог. Переместим код, который мы уже написали в указанный каталог и выполним его:

$ mkdir exampDir

$ move example.py exampDir

$ cd exampDir

$ py example.py

py

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

Создайте другой файл с именем setup.py в той же папке. Здесь мы сохраним подробную информацию о конфигурации, о том, как мы хотим скомпилировать нашу программу. Пока мы просто добавим в него пару строк кода:

from distutils.core import setup # Need this to handle modules

import py2exe 

import math # We have to import all modules used in our program

setup(console=['example.py']) # Calls setup function to indicate that we're dealing with a single console application

py

Теперь откройте командную строку от имени администратора и перейдите в каталог, чтобы запустить файл setup.py:

$ cd exampDir

$ python setup.py py2exe

running py2exe

*** searching for required modules ***

*** parsing results ***

Most will agree that Python is easy to learn and write. When it comes to sharing that beautiful code, there’s one problem, though! Sharing your program with someone that doesn’t know Python is a challenge! Your fellow Pythonistas will be perfectly able to pip install your package or run a Python script you send them. But what about your boss? The non-programmers? This is where PyInstaller comes to play.

PyInstaller bundles your application into a single, runnable file you can share with anyone. No Python installation is required; just click and run! PyInstaller makes life easier for those that want to share their work. This article explains how PyInstaller works and what limitations there are. Finally, we’ll convert a Python program into a runnable file that can be shared with anyone.

Table of Contents

  • 1 How to install PyInstaller
  • 2 How PyInstaller works
  • 3 Creating a binary using PyInstaller
  • 4 Limitations
  • 5 PyInstaller tips and tricks
  • 6 Learn more about PyInstaller

How to install PyInstaller

You know the drill. Use pip install, Poetry, or Pipenv to install the package. The package name you need is pyinstaller, so for a regular pip install, that would be:

pip install pyinstaller

If you don’t know these tools, please follow the links and read up about them. If you use Poetry or Pipenv, add it as a developer dependency.

Supported platforms

PyInstaller officially supports Windows 8 and up, macOS, and Linux, with some limitations you’ll learn about further on.

How PyInstaller works

PyInstaller has two modes:

  1. Single directory mode
  2. one-file mode

The most elegant (in terms of distributing your program) is the one-file mode. It’s a single file, e.g., a .exe on Windows, that you can share with someone. This single file extracts itself into a temporary directory and runs the extracted code. The other mode (single directory) is a directory you can share with someone. It contains all the required files in a single, flat directory.

Let’s dive deeper and see how PyInstaller does its magic.

The Bootloader

PyInstaller creates a so-called bootloader, which bootstraps your Python program. This process is separated from your actual Python program. Hence you can expect to see two processes being launched: first the bootloader and then your own Python code. When you pip install PyInstaller, this bootloader is created once. The installation will only succeed if the bootloader got built.

Finding the needed module files

When packaging your Python project, PyInstaller must determine which modules to include. E.g., most software will have at least a couple of import statements, importing either built-in Python modules or externally downloaded modules. PyInstaller analyses your code and finds all the import statements. It does so recursively. For example, if you import a package like the built-in JSON library, it will load the JSON module’s code and analyze any imports found in there. This process repeats until it has all the required files to include.

Some modules do more peculiar things, like using importlib to import other modules. In these cases, you can manually supply pyinstaller the extra modules to include. PyInstaller includes ‘hooks’ for well-known packages that do these things, so chances are you won’t ever need to do this!

Specifying data files

If your software requires data files, you’ll need to tell PyInstaller explicitly. This is done by modifying the so-called spec file PyInstaller creates on the first run. This spec file tells PyInstaller exactly how to process your script. This is an advanced topic, and if you need to do this, I suggest you read the manual page on spec files.

Creating a binary using PyInstaller

Let’s start with an extremely simple use case: a single Python file called hello.py with the following contents:

print("Hello world")

We can use the following command to package our script:

pyinstaller hello.py

After running this command, this is what happens:

  • PyInstaller analyzes your script for any import
  • A hello.spec file is created
  • A build folder is created
  • A dist folder is created, containing a folder called hello

The dist/hello folder contains all the files required to run our program, including an executable. On Linux and macOS, this executable is called hello, on Windows it will be called hello.exe. This executable file is the bootloader I mentioned before. Run it and see for yourself if it works!

If you check the size of the generated directory, you’ll notice that it’s pretty big for such a small script. In my case (on Linux) it’s 15 megabytes, but you need to consider that there’s a lot of overhead. E.g., this dist dir includes a copy of the Python core library, several required libraries, etcetera.

Creating a single file

We’ve used the default settings, creating a directory in dist containing your project. If you want to create a single file, you need to use the -F or --onefile option. I like the latter because it’s easy to remember:

pyinstaller --onefile hello.py

PyInstaller will ask if it may remove the previous output directory, which is OK. The output will this time be a single file: hello.exe on Windows or simply hello on Linux and macOS. Run it to verify if everything worked.

Importing external libraries

PyInstaller uses the PATH to find modules and packages. So if you used Poetry or Pipenv or a plain old virtualenv to install something like requests, PyInstaller will be able to package it with your software just fine. Just make sure you activated the virtual environment so that PyInstaller can find the library in your PATH.

E.g., the following program works flawlessly as long as PyInstaller can find requests:

import requests

print("Hello world")
r = requests.get("https://example.org")
print(r.status_code)
print(r.text)
print("Bye")

PyInstaller supports most of the well-known Python libraries out there, including the more advanced ones like:

  • NumPy (which includes a lot of compiled C/C++ code)
  • Pandas
  • Tensorflow
  • Matplotlib
  • PyQT (for GUI programming)
  • Pillow

You can refer to the PyInstaller wiki on GitHub for a more complete list, although this list is not exhaustive. You are encouraged just to try, as most packages will work just fine.

Useful PyInstaller command line options

Here are some more options you might need:

Option What it does
-D, --onedir Output a directory (the default)
-F, --onefile Output a single executable file
-n NAME, --name NAME Use this name for the app, instead of using the script’s basename
--windowed Don’t open a console for standard input and output on Windows and macOS. This option also creates a macOS .app bundle on macOS. Use –icon <file> to specify an icon for the macOS app. This option is ignored on Linux.
--splash <image file> Show a splash image during loading. Only useful in combination with --windowed and for large, slow-loading programs. This is experimental and does not work on macOS.
-i, --icon FILE.ico Apply the given icon to the Windows executable file.
A selection of PyInstaller command line options

Limitations

Unfortunately, it’s not all shimmer and shine.

Pyinstaller is not a cross-compiler, which means it can’t create binaries for macOS or Linux from Windows and vice versa. You have to run pyinstaller on each platform that you want to support. E.g., if you want to release your software for both Windows and macOS, you’ll have to build the Windows file on Windows and the macOS file on a macOS machine.

If your software uses external tools and applications, you must add them manually. If these tools are platform specific, you won’t be able to distribute to other platforms unless you find alternative tools that you can include on these other platforms.

Although sharing your code with someone else, using the same OS will work flawlessly most of the time, your mileage may vary when you are on different versions of an OS. If you want to use PyInstaller to distribute your package to many people, you’ll have to put a lot more care into the packaging. The PyInstaller documentation contains more detailed information per OS.

PyInstaller tips and tricks

Here are a few tips and tricks you might need.

Determine if your code is running in a bundle

import sys
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
    print('running in a PyInstaller bundle')
else:
    print('running in a normal Python process')

Add a splash screen

You can add a splash screen to your bundle, but it is an experimental feature that does not work on macOS. The bootloader shows the splash screen, so the user gets some affirmation that the program is loading/unpacking. You can even display some custom, dynamic text on the splash screen.

To show a splash screen, create an image and specify it with the --splash <image file> option.

Manually add modules that PyInstaller did not recognize

Sometimes PyInstaller does not find all the imports in your code. This can happen, for example, when importing modules from within a function. You can add the missing libraries manually with the --hiddenimport MODULENAME parameter. E.g., to add a missing colorama import, you would use:

pyinstaller --hiddenimport colorama myfile.py.

To add multiple packages, simply repeat the same option multiple times.

Learn more about PyInstaller

I cover PyInstaller more extensively in my course, Python Fundamentals II. In this course, you’ll get real-world practice by packaging the project we build in Python Fundamentals I. While doing so, we’ll run into a couple of typical problems. I’ll teach you how to diagnose and fix such issues.

In addition, the PyInstaller documentation is excellent, so I highly recommend you skim through there to see if there’s more that interests you.

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

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

pip install PyInstaller

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

pyinstaller --version

Я использую 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, который содержит такой код.

import time
name = input("Введите ваше имя ")
print("Ваше имя ", name)
time.sleep(5)

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

pyinstaller --onefile simple.py

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

папки, BUILD и DIST, а также файл .spec

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

 исполняемый файл

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

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

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

import time
# pip install pandas
import pandas as pd


def count_records():
    data = pd.read_csv('netflix_titles.csv')
    print("Всего фильмов:", data.shape[0])


if __name__ == "__main__":
    count_records()
    time.sleep(5)

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

pyinstaller --add-data "netflix_titles.csv;." simple1.py

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

Синтаксис add-data:

  • add-data <source;destination> — Windows.
  • add-data <source:destination> — Linux.

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

Добавление файлов с данными

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

...
a = Analysis(['simple1.py'],
             pathex=['E:\\myProject\\pyinstaller-tutorial'],
             binaries=[],
             datas=[('netflix_titles.csv', '.')],
...

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

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

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

import time
import sys
import os
# pip install pandas
import pandas as pd


def count_records():
    os.chdir(sys._MEIPASS)
    data = pd.read_csv('netflix_titles.csv')
    print("Всего фильмов:", data.shape[0])


if __name__ == "__main__":
    count_records()
    time.sleep(5)

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

pyinstaller --onefile --add-data "netflix_titles.csv;." simple1.py

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

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

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

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

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

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

pyinstaller --onefile --add-data "netflix_titles.csv;." — hidden-import "os" simple1.py

Файл spec

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

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

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

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

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

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

import time
import tensorflow as tf


def view_model():
    print(tf.__version__)


if __name__ == "__main__" :
    model = view_model()
    time.sleep(5)

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

pyinstaller -F simpleModel.py

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

...
File "site-packages\tensorflow_core\python_init_.py", line 49, in ImportError: cannot import name 'pywrap_tensorflow' from 'tensorflow_core.python' 

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

$ pyi-makespec simpleModel.py -F
wrote E:\pyinstaller-tutorial\simpleModel.spec
now run pyinstaller.py to build the executable

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

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

...
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='simpleModel',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=True )

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

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

# -*- mode: python ; coding: utf-8 -*-

block_cipher = None
import os
spec_root = os.path.realpath(SPECPATH)
options = []
from PyInstaller.utils.hooks import collect_submodules, collect_data_files
tf_hidden_imports = collect_submodules('tensorflow_core')
tf_datas = collect_data_files('tensorflow_core', subdir=None, include_py_files=True)

a = Analysis(['simpleModel.py'],
             pathex=['E:\\myProject\\pyinstaller-tutorial'],
             binaries=[],
             datas=tf_datas + [],
             hiddenimports=tf_hidden_imports + [],
             hookspath=[],
...

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

Хуки

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

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

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

pyinstaller simpleModel.spec

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

Вывод:

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

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

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как изменить время выключения экрана windows 10
  • Kyocera ecosys m2540dn драйвер windows 7
  • Kb2545698 что за обновление windows 7
  • Assassins creed liberation hd не запускается windows 10
  • Xshell для windows 7