Python compiler to one file

Compile Python Scripts to Executable Files

Writing scripts that are based on Python libraries and are meant to be executed more than once is a good practice. It is a good way to ensure that your code is not executing on a system that may not have all the required Python modules installed. Compiling a python script to an executable file is also a good practice. This will ensure that script runs independently of the Python installed on the system. This tutorial will discuss different ways to compile Python scripts to executable files. This includes compiling the script on Linux and windows.

Prerequisite:

For compiling the python script into a .exe file first, we need a Python script here we created a simple python script that gives you simple messes when clicking one button.

import tkinter as tk root= tk.Tk() canvas1 = tk.Canvas(root, width = 299, height = 299, bg='black') canvas1.pack() def hello (): label1 = tk.Label(root, text= 'Hello Programmer!', fg='red', font=('helvetica', 12, 'bold')) canvas1.create_window(150, 200, window=label1) button1 = tk.Button(text='say hello',command=hello, bg='white',fg='black') canvas1.create_window(150, 150, window=button1) root.mainloop()

How to Compile a python script for windows:

We are going to use three python libraries to Compile a python script into an executable file for windows

Читайте также:  Постепенное появление элементов css

1.Compiling the script using Pyinstaller library:

Step 1:

To install pyinstaller use the following command in the command prompt.

Pyinstaller: With PyInstaller, you can bundle your Python application and all of the packages it relies on into a single, compact executable. This reduces the need to install dozens or hundreds of packages when deploying an application or when helping students set up their programming environment. PyInstaller supports Python 2 and above.

Step 2:

Create a folder and save the python script in it. For example, we created a folder name exe_app and saved my python script named app.py in it.

Step 3:

Open a command prompt in the same folder where our python script is saved and type the following command and press enter.

pyinstaller --onefile app.py

Output:

Step 4:

After running the command you can see that more files and folders are created in the root folder. There you can see folder name dist in that you can find the . EXE file.

You can open the app.exe file to see it running like a normal windows application, you can click on the say hello button that shows the message.

2. Compiling the script using Py2exe library:

Step 1:

To install Py2exe use the following command in the command prompt.

Py2exe: py2exe library is the same as the pyinstaller library.

Step 2:

You need to create a new file setup.py at the same directory where you have the script. This file contains the below parameters.

from distutils.core import setup import py2exe setup(windows=['app.py'])

in place of app.py, you can add your python file name. And if your script runs in the console replace windows for the console.

Step 3:

Open a command prompt in the same folder where our python script is saved type the following command and press enter.

Step 4:

After running the code folder name dist is created in the root folder and in the dist folder, you can find that app.exe is created.

3. Compiling the script using the auto-py-to-exe library:

Step 1:

To install auto-py-to-exe use the following command in the command prompt.

auto-py-to-exe (GUI Tool): auto-py-to-exe is also a library that converts Python scripts into executable Windows programs, able to run without requiring a Python installation. But it has a graphical interface.

Step 2:

To open the auto-py-to-exe use the following command in the command prompt.

Output:

As you can see it opens a graphical interface that is already self-explanatory you just have to select the app.py file and select what you want in the given option and press on convert.py to .exe and that’s it. Then it will automatically open the folder of the exe file that you lunch.

How to Compile a python script for Linux:

Step 1:

For Linux, we can use the pyinstaller library as well but for compiling python script for Linux we need to do this process on a Linux system otherwise it will automatically make a .exe file

To install pyinstaller use the following command in the terminal.

Step 2:

Same as before creating a folder and saving the python script in it. For example, we created a folder name exe_app and saved my python script named app.py in it.

Step 3:

Open a terminal in the same folder where our python script is saved type the following command and press enter.

pyinstaller --onefile app.py

Output:

Step 4:

After running the command you can see that more files and folders are created in the root folder. There you can see folder name dist in that you can find the file name app.

you can launch the app file by using the following common in the terminal in the same directory.

Conclusion:

It is sometimes necessary to compile (aka build) a python script into an executable file that can be run independently of a python environment. Python does come with its built-in tools for doing so by itself, and in this post, we looked at the many types of the python library that you can easily create a standalone executable program on windows and Linux. for Windows systems, we used pyinstaller and py2exe. We also looked at the auto-py-to-exe, which is a graphical frontend for automatic script compilation. For Linux, we examined pyinstaller. All of these methods are easy to use and if you have any questions don’t hesitate to comment below!

Источник

Convert Python Scripts to Windows Executables (.py to .exe) — Pyinstaller and Pandas | 2022 WORKING VERSION

Python and pandas are a great team for data science. But what if you need to deliver a script to a Windows client who does not have Python installed? This is a quick tutorial for converting Python scripts ( .py ) to standalone, one-file Windows executables ( .exe ).

Get a 20Mb exe file that is fully functional on every Windows machine! tl;dr: If you need one standalone file that works on machines without a Python distrubution go for Pyinstaller. Just be aware of some overhead when importing certain libraries.

Python to exe

  • standalone
  • one file, i.e. one .exe-file with everything included
  • no installer for client setup
  • should work “plug-’n’-play”
  • as small as possible

In the end I managed to get exactly what I wanted but it was a long and troublesome way to go.

There are plenty of python-to-exe scripts/programs/compilers out there but after testing the most used ones only Pyinstaller satisfied my needs. None of the other fulfilled all the above-listed criteria!

Pyinstaller & Pandas

I tried Pyinstaller some years ago and remembered, that somehow I got it working. The big issue with Pyinstaller is that some Python packages do not work out-of-the-box and require some overhead, particular installations, dependencies or settings which can be quite troublesome to figure out.

Out there are tons of outdated docs, stackoverflow questions, guidelines and medium articles that simply didn’t help. Only a few pointed to the right direction.

Some banana skins

Let’s get to the point. Some Donts first:

Workflow

1. Set up a virtual environment

You simply cannot skip this step as otherwise all your global Python libraries you ever installed will end up in the .exe which can lead to a couple of GB.

Also, do not use conda! I tried with conda envs but simply failed. The trick here is to go for virtualenv and only use pip to install packages.

Install virtualenv and create the environment in your project folder.

Источник

Компилируем код Python в файл exe

Код, написанный на Python, позволяет решать много прикладных задач: автоматизация отчетности, алгоритмы поиска, анализа и пр. Однако не у всех потенциальных пользователей может быть установлен сам Python и тем более не все являются экспертами в программировании. Выручить может программа, которая будет отрабатывать написанный вами код без установки библиотек Python и необходимой оболочки. Одним из таких решений может быть компиляция кода Python а файл exe. Дальше простым языком мы постараемся объяснить, как его скомпилировать и какие есть нюансы.

Для начала Вам необходимо скачать компилятор pyinstaller, для чего вам понадобится команда:

Далее ваш код в формате. py необходимо разместить в системную папку Scripts.

Путь к этой папке обычно выглядит так:

Если Вы инсталлировали Python в другое место, соответственно ищите папку там.

Далее приступаем собственно к компиляции, для чего: выделяем путь к папке Scripts в окне браузера, вместо него набираем команду cmd и жмем Enter.

У Вас сразу будет указан верный путь к файлу:

В продолжение строки с директорией файла необходимо набрать команду: pyinstaller Report.py —onefile

Где Report.py – это имя вашего файла, — onefile – означает, что программа будет скомпилирована в единый файл.

Нажимаем Enter. Pyinstaller приступает к сборке программы.

В зависимости от размера кода и количества, используемых в нем библиотек, время сборки программы может занять 5-15 мин. Успешностью завершения будет являться следующее сообщение:

Готовый файл находим в папке dist.

Данный метод компиляции не оптимизирует включение только необходимых библиотек, поэтому нужно быть готовым к тому, что его размер будет занимать достаточно объема. В нашем случае код из 120 строк с библиотекой Pandas и Datetime собран в программу весом почти 220 Mb. Теперь данным файлом может пользоваться любой сотрудник.

Хотелось бы обратить внимание на следующие нюансы: если вы компилируете файл на 64 битной OS Windows 10, то он не запустится на 32 битной OS Windows 7.

Если же файл будет скомпилирован на 32 битной OS Windows 7, то его можно будет запустить как на 32 битных, так и на 64 битных OS Windows 7/10.

Источник

Оцените статью