How to compile python to exe
How to compile python to exe
Как создать exe файл для Python кода с помощью PyInstaller
Установка PyInstaller
Установка PyInstaller не отличается от установки любой другой библиотеки Python.
Вот так можно проверить версию PyInstaller.
Я использую PyInstaller версии 4.2.
Создание exe файла с помощью PyInstaller
PyInstaller собирает в один пакет Python-приложение и все необходимые ему библиотеки следующим образом:
Возьмем в качестве примера простейший скрипт на Python c названием simple.py, который содержит такой код.
Создадим один исполняемый файл. В командной строке введите:
Python создает каталог распространения, который содержит основной исполняемый файл, а также все динамические библиотеки.
Вот что произойдет после запуска файла.
Добавление файлов с данными, которые будут использоваться exe-файлом
Есть CSV-файл netflix_titles.csv, и Python-script, который считывает количество записей в нем. Теперь нужно добавить этот файл в бандл с исполняемым файлом. Файл Python-скрипта назовем просто simple1.py.
Создадим исполняемый файл с данными в папке.
Можно увидеть, что файл теперь добавляется в папку DIST вместе с исполняемым файлом.
Также, открыв spec-файл, можно увидеть раздел datas, в котором указывается, что файл netflix_titles.csv копируется в текущую директорию.
Добавление файлов с данными и параметр onefile
Скрипт обновлен для чтения папки TEMP и файлов с данными. Создадим exe-файл с помощью onefile и add-data.
После успешного создания файл simple1.exe появится в папке DIST.
Можно скопировать исполняемый файл на рабочий стол и запустить, чтобы убедиться, что нет никакой ошибки, связанной с отсутствием файла.
Дополнительные импорты с помощью Hidden Imports
Исполняемому файлу требуются все импорты, которые нужны Python-скрипту. Иногда PyInstaller может пропустить динамические импорты или импорты второго уровня, возвращая ошибку ImportError: No module named …
Для решения этой ошибки нужно передать название недостающей библиотеки в hidden-import.
Например, чтобы добавить библиотеку os, нужно написать вот так:
Файл spec
Файл spec — это первый файл, который PyInstaller создает, чтобы закодировать содержимое скрипта Python вместе с параметрами, переданными при запуске.
PyInstaller считывает содержимое файла для создания исполняемого файла, определяя все, что может понадобиться для него.
Если у вас есть какое-либо из нижеперечисленных требований, то вы можете изменить файл спецификации:
Например, есть скрипт simpleModel.py, который использует TensorFlow и выводит номер версии этой библиотеки.
Компилируем модель с помощью PyInstaller:
После успешной компиляции запускаем исполняемый файл, который возвращает следующую ошибку.
Исправим ее, обновив файл spec. Одно из решений — создать файл spec.
Команда pyi-makespec создает spec-файл по умолчанию, содержащий все параметры, которые можно указать в командной строке. Файл simpleModel.spec создается в текущей директории.
Если использовать параметр по умолчанию или onedir, то вместе с exe-разделом будет также и раздел collect.
Можно открыть simpleModel.spec и добавить следующий текст для создания хуков.
Создаем хуки и добавляем их в hidden imports и раздел данных.
Файлы хуков расширяют возможность PyInstaller обрабатывать такие требования, как необходимость включать дополнительные данные или импортировать динамические библиотеки.
Обычно пакеты Python используют нормальные методы для импорта своих зависимостей, но в отдельных случаях, как например TensorFlow, существует необходимость импорта динамических библиотек. PyInstaller не может найти все библиотеки, или же их может быть слишком много. В таком случае рекомендуется использовать вспомогательный инструмент для импорта из PyInstaller.utils.hooks и собрать все подмодули для библиотеки.
Скомпилируем модель после обновления файла simpleModel.spec.
Скопируем исполняемый файл на рабочий стол и увидим, что теперь он корректно отображает версию TensorFlow.
Вывод:
PyInstaller предлагает несколько вариантов создания простых и сложных исполняемых файлов из Python-скриптов:
Установка Auto PY to EXE
Установка через pip
При помощи следующей команды можно установить текущую версию Auto PY to EXE.
Установка с GitHub
Также можно выполнить установку напрямую с GitHub. Для установки Auto PY to EXE с GitHub необходимо сначала клонировать репозиторий GitHub.
Можно также проверить версию при помощи следующей команды:
Текущая версия Auto PY to EXE 2.9.0 и теперь она установлена на ваш компьютер.
Открываем приложение
Чтобы открыть Auto PY to EXE, нужно выполнить в терминале следующую команду:
Откроется удобное приложение с GUI:
Интерфейс пользователя Auto PY to EXE
Процесс преобразования
Шаг 1. Добавляем местоположение файла
Добавляем местоположение файла
Я добавил местоположение основного файла Python моего проекта. Здесь я использую для примера один из своих проектов на Python. Это приложение с GUI, визуализирующее различные алгоритмы сортировки. О создании этого проекта можно прочитать здесь: Build a Sorting Algorithm Visualizer in Python
Шаг 2. Выбор «One Directory» или «One File»
One directory или One file
Шаг 3. Выбор «Console Based» или «Window Based»
После этого нужно будет выбрать тип приложения: консольное (Console Based) или оконное (Window Based). Если выбрать «Window Based», то это скроет весь консольный вывод приложения. Если ваш проект генерирует консольный вывод, то нужно выбрать «Console Based». Если у вас приложение с GUI или вам не нужно отображать пользователю консольный вывод, то выберите «Window Based». Я выбрал второй вариант, потому что моё приложение имеет GUI.
Console Based или Window Based
Шаг 4. Преобразование
Нажмите кнопку для преобразования
Для завершения процесса придётся немного подождать.
Папка с результатами
После завершения процесса можно будет выбрать опцию открытия папки с результатами.
Готово! Наш проект на Python теперь преобразован в исполняемый файл. Его можно запускать на других компьютерах без необходимости установки Python.
Ресурсы
На правах рекламы
Серверы для всех, в том числе, и для разработчиков! VDS с посуточной оплатой на базе новейших процессоров AMD EPYC и хранилища на основе NVMe дисков от Intel для размещения проектов любой сложности, создавайте собственную конфигурацию сервера в пару кликов!
How can I make an EXE file from a Python program? [duplicate]
I’ve used several modules to make EXEs for Python, but I’m not sure if I’m doing it right.
How should I go about this, and why? Please base your answers on personal experience, and provide references where necessary.
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
py2exe is probably what you want, but it only works on Windows.
PyInstaller works on Windows and Linux.
Py2app works on the Mac.
I found this presentation to be very helpfull.
There are many deployment options for Python code. I’ll share what has worked well for me on Windows, packaging command line tools and services using py2exe and InnoSetup. I’ll demonstrate a simple build script which creates windows binaries and an InnoSetup installer in one step. In addition, I’ll go over common errors which come up when using py2exe and hints on troubleshooting them. This is a short talk, so there will be a follow-up Open Space session to share experience and help each other solve distribution problems.
Also known as Frozen Binaries but not the same as as the output of a true compiler- they run byte code through a virtual machine (PVM). Run the same as a compiled program just larger because the program is being compiled along with the PVM. Py2exe can freeze standalone programs that use the tkinter, PMW, wxPython, and PyGTK GUI libraties; programs that use the pygame game programming toolkit; win32com client programs; and more. The Stackless Python system is a standard CPython implementation variant that does not save state on the C language call stack. This makes Python more easy to port to small stack architectures, provides efficient multiprocessing options, and fosters novel programming structures such as coroutines. Other systems of study that are working on future development: Pyrex is working on the Cython system, the Parrot project, the PyPy is working on replacing the PVM altogether, and of course the founder of Python is working with Google to get Python to run 5 times faster than C with the Unladen Swallow project. In short, py2exe is the easiest and Cython is more efficient for now until these projects improve the Python Virtual Machine (PVM) for standalone files.
Not on the freehackers list is gui2exe which can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts.
Use cx_Freeze to make exe your python program
py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
I’m trying to convert a fairly simple Python program to an executable and couldn’t find what I was looking for, so I have a few questions (I’m running Python 3.6):
The methods of doing this that I have found so far are as follows
Here is what I’ve tried/what problems I’ve run into.
8 Answers 8
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
See the original script in my blog.
setup.py:
Python 3.6 is supported by PyInstaller.
Open a cmd window in your Python folder (open a command window and use cd or while holding shift, right click it on Windows Explorer and choose ‘Open command window here’). Then just enter
The simplest way to use it is by entering on your command prompt
For more details on how to use it, take a look at this question.
There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.
GUI:
Output:
Alternatively use pyinstaller directly:
I can’t tell you what’s best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, ’17) to version 5.0.1 and it supports Python 3.6.
The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html
I have not tried it out yet, so I’m going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.
Now you can convert it by using PyInstaller. It works with even Python 3.
I’ve been using Nuitka and PyInstaller with my package, PySimpleGUI.
Nuitka There were issues getting tkinter to compile with Nuikta. One of the project contributors developed a script that fixed the problem.
If you’re not using tkinter it may «just work» for you. If you are using tkinter say so and I’ll try to get the script and instructions published.
PyInstaller I’m running 3.6 and PyInstaller is working great! The command I use to create my exe file is:
This is as close to getting what looks like a Winforms program to run that was written in Python.
There is PySimpleGUI GUI based solution that uses PyInstaller. It uses PySimpleGUI. It’s called pysimplegui-exemaker and can be pip installed.
pip install PySimpleGUI-exemaker
To run it after installing:
1.) It may not work for python 3.9 on some devices I guess.
2.) While installing python, if you had selected ‘add python 3.x to path’, open command prompt from start menu and you will have to type pip install auto-py-to-exe to install it. You will have to press enter on command prompt to get the result of the line that you are typing.
How to Find the Magnitude of a Vector in Numpy : Various Methods
Are you searching for how to compile python to exe? Here are some easy tricks to achieve with the help of these modules- Pyinstaller, auto-py-to-exe, Py2exe.
Sample Python Script creation –
Before proceeding to this article, We need to create a sample python script that will be used for the demonstration. Here I am creating a sample python script that will output the sum of two numbers provided by the user –
The above sample is saved by the name of sum.py. You may download it directly from here.
1. Compile Python to Exe Using Pyinstaller –
This section will explain how to convert py to exe using pyinstaller? All you need is to follow the below steps for compiling python to exe in Linux as well as Windows Operating System.
Step 1: First, Install Pyinstaller using pip or any other package manager.
I have python 3.xx version, that’s why I am using the pip3 command.
Installing Pyinstaller using pip3 command
Step 2: Go to the path where the python script is stored. You may directly open the command prompt on that location using shift + Right Click, or change the path using cd command in prompt.
Python Script Directory
Step 3: Most importantly, once you are on the same path where you have the sample python script (for example sum.py), Use the below command.
Python Script Dist Directory
You will get the python exe file under the dist folder on the same location. I hope this quick pyinstaller tutorial on python will help you to get the exe conversion.
Python Script Exe File
2. Compile a Python Program to Exe using auto-py-to-exe (GUI Tool) –
Using this GUI (Graphical User Interface) Tool, You can easily build python to exe in a few steps-
Step 1: Firstly, Install the auto-py-to-exe using pip package manager –
Installing auto-py-to-exe using pip3 command
Step 2: Lunch this auto-py-to-exe, By entering auto-py-to-exe into cmd.
Command to run auto py to exe GUI
Step 3: Once the application is launched, You need to select the python script path into Script Location field.
Selection of Python Script to Convert to exe
Step 4: Now, You need to decide that you need the exe file as One Directory or as one file. You need to choose accordingly. Here if you so many python files dependencies for the application, You need to choose the main python file.
If you choose “One Directory” as an option you will get exe in the output folder (path is user-configurable) with dependencies file. If you opt “one file option”, your all code dependencies will be in one exe file.
Exe File for the Python Script
3. Convert Python File to exe using Py2exe-
Let’s see how can you use Py2exe to compile a python script to exe file.
Step 1: Firstly install Py2exe. Using pip –
Installing Py2exe using pip3 command
Step 2: You need to create a new file setup.py at the same directory where you have the script. This file contains this below parameters-
Here above sum.py is a dummy python script for demonstration for the py2exe functionality. Here you may put your own library.
Step3: Now the last step is to launch the command prompt and type the below command to convert the python script to exe. Make sure you must be running the command from the same directory where the setup.py file is available.
Running the setup python script with Py2exe
This will create the executable file into dist folder in the same directory where we have the sample python script (sum.py)
Conclusion –
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.