Code

Creating an EXE from a Python Script: PyInstaller and Other Methods

Creating an EXE from a Python Script: PyInstaller and Other Methods

Master the profession of Python developer with an emphasis on artificial intelligence

Learn more

In order to run a program written in Python and having the .py extension, you need an interpreter - a program that executes the code. However, Windows users are usually accustomed to executable files with the .exe extension, which can be opened with a simple double-click, without the need to take additional steps.

There are several ways to convert a Python script into an EXE file.

  • PyInstaller is a multi-functional tool designed to generate EXE files.
  • Auto-Py-to-Exe is a program that offers the user a graphical interface for work.
  • cx_Freeze is one of the ways to convert software into EXE files.
  • Py2exe is a utility designed to create executable files.
  • Nuitka is a tool that converts Python code into machine code.
  • When choosing a tool for creating EXE files, it is worth considering several factors, such as ease of use, functionality, and support for the required programming languages. There are many utilities available, each with its own unique features.

    One popular solution is Inno Setup, which allows you to create installation packages for Windows. This application is highly flexible and also supports scripts, allowing you to fine-tune the installation process.

    Another option is NSIS (Nullsoft Scriptable Install System). This tool is also designed for creating installers and offers a wide range of customization options. It is suitable for both simple and complex projects.

    If you work with Python, PyInstaller is worth considering. This utility allows you to package your scripts into executable files and supports a variety of libraries, making it a great choice for Python developers.

    For C# users, Visual Studio is a good choice, as it includes all the necessary tools for compiling and creating EXE files, as well as provides an integrated development environment.

    Finally, if you need to create a GUI application, you should consider frameworks like Electron or Qt, which allow you to create cross-platform applications and compile them into EXEs.

    Ultimately, the choice of tool depends on your needs and technology stack. Explore the available options and choose the one that best suits your needs.

Before using any of the tools mentioned, make sure you have Python 3.11 or 3.12 installed on your device, obtained from the official resource.

Read also:

Running Python as in Offline and online: a step-by-step guide for beginners.

Requires Windows 10 or later. Please note that some utilities may not be compatible with the latest versions of Python, as their updates are not always synchronized with the language itself.

PyInstaller: The Leading Tool for Generating EXE Files

PyInstaller is a utility that converts Python scripts into standalone executable programs. The resulting EXE file contains not only the code itself, but also the Python interpreter, as well as all the necessary libraries and resources. Thanks to this, the application can function in environments where Python is not installed.

PyInstaller is very popular, and there are several reasons for this.

What's good about it:

  • The most common and reliable method of distributing Python programs is to create EXE files. This approach allows the user downloading the program to avoid having to install Python and manage dependencies themselves.
  • There is a "Single File" mode, which converts the application to EXE format without creating additional directories.
  • PyInstaller has the ability to create graphical applications that do not display an auxiliary console, making the final product's interface more presentable.
  • The flexibility of the system allows for detailed customization of which modules and resources will be activated. You can edit the SPEC file and apply hooks to libraries that aren't integrated automatically.

What's bad:

  • Even the most basic program, after packaging, becomes an EXE file tens of megabytes in size. This is because it comes with a Python interpreter and all the necessary components for its operation.
  • When selecting the "Single File" mode, the application takes a little longer to load. First, it unpacks into a temporary directory, and only then does it launch.
  • Not all dependencies are added automatically. Often, you need to manually work with dynamic imports, native libraries, or resources.
  • There are certain platform limitations. An EXE application can only be created on the Windows operating system. To compile applications for Linux or macOS, you must use the corresponding systems.
  • There are risks associated with system libraries: on Windows, DLL files or on Linux, SO files may exhibit unpredictable behavior if they are not correctly linked.
  • EXE files created with PyInstaller sometimes cause false positives from antivirus software, especially if they are not digitally signed.

You will need the PIP package manager for this work.

Read also:

Installing PIP for Python: Step-by-Step Guide and Key Commands

To get started with PIP, the package manager for Python, you first need to install it. Let's look at the main steps of this process.

1. Check if Python is installed on your device. To do this, open the command line and enter the command `python —version` or `python3 —version`. If Python is installed, you will see its version.

2. If PIP is not present, download the get-pip.py script. This can be done by going to the official PIP website or using the command `curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py` in the terminal.

3. Once the script has downloaded, run it using Python. Enter `python get-pip.py` or `python3 get-pip.py`, depending on your installation.

4. Verify that PIP is installed correctly by running `pip —version` or `pip3 —version`. This will confirm that the package manager is working and ready to use.

Now that PIP is installed, here are some basic commands that might be useful in your work:

`pip install ` — to install the desired package.
`pip uninstall ` — to remove the package.
`pip list` — to display all installed packages.
` `pip freeze` — to get a list of installed packages in a format suitable for writing to a requirements.txt file.

Following these steps, you can easily install and start using PIP for package management in Python.

Please enter the following command in the terminal:

PyInstaller will be automatically installed along with Python.

Now we need a Python script, which will be the basis for our executable file.

Let's create a Python program that will display a welcome message in a window using the Tkinter graphics library.

First, you need to save this code to a file with the .py extension and name it main_py_to_exe.py. Then, open a command prompt in the folder where this file is located and run the following command to create an EXE file from your Python script:

PyInstaller is a tool that converts Python scripts into EXE executables.

The key parameter —onefile— allows you to compile the entire application into a single EXE executable file. The resulting file includes all necessary elements, such as the Python interpreter and used libraries. This solution helps reduce the size of the distribution, although it should be noted that the final file size can be quite impressive.

The option —noconsole— is designed to hide the console window when the application is running. This is especially important for graphical interfaces, as it allows the user to focus solely on the visual part, eliminating the appearance of an unnecessary console.

As a result of the previous command, PyInstaller will create the dist and build directories, and also create the main_py_to_exe.spec file.

  • The dist folder contains various technical and service files, including compiled versions and logs. If your goal is only to obtain an executable file, you can safely delete this folder.
  • The build folder contains our executable file.
  • main_py_to_exe.spec is a file that contains settings for application configuration.

Let's immediately open the build folder and check how our assembled application works. Run the main_py_exe.exe file, and the following window should appear on the screen:

Screenshot: Skillbox Media

Let's add an icon to our application. To do this, you need to place a file with the .ico extension in the same folder with the SPEC file. As an example, you can download any free icon from the specified website. In our case, this is the ChatGPT icon. Then, open the .spec configuration file in a text editor and add a line with the ICO file name to the section of code responsible for EXE settings.

First, save the file. Then, open a command prompt in this folder and enter the following command:

This command will rebuild the EXE file based on the parameters specified in the SPEC file. As a result, the application now has its own icon. Here's what we've achieved:

Screenshot: Windows Explorer / Skillbox Media

All information about SPEC file settings is provided in the official PyInstaller documentation.

Auto-Py-to-Exe — a tool with a user-friendly GUI

Auto-Py-to-Exe is a user-friendly GUI front-end for PyInstaller. While it's not a replacement for PyInstaller, using this shell significantly simplifies the process. Instead of typing commands in the terminal, users are presented with a window where they can select the desired script, define packaging parameters, add an icon, and include the necessary files and resources.

What's great about it:

  • Everything is very clear: all the settings are presented right at your fingertips, you can see which features are activated, and it's easy to figure out exactly what has been changed.
  • The program notifies the user if the path to the script is incorrect, if the icon does not match the required format, or if the Python version is incompatible.
  • Configurations can be saved, allowing you to build an EXE with the same parameters if needed. To do this, simply load a previously saved JSON file.

What's bad:

  • Auto-Py-to-Exe is not a full-fledged replacement for PyInstaller and has inherited all of its limitations. Projects with a complex structure and non-standard dependencies may require additional manual configuration.
  • In some cases, you must manually define additional modules or specify paths to resources, otherwise an error may occur when launching the program.
  • The interface operates based on a built-in browser, which is most often Chrome. If any problems with this browser occur, errors or unusual behavior may occur.
  • An EXE file created on one computer may not always run correctly on another device. This is especially true if the operating systems differ in Windows versions or the necessary libraries are missing.
  • If you are working on large-scale projects with numerous dependencies, a complex architecture, or strict requirements for the minimum size of the final build, then Auto-Py-to-Exe's capabilities may not be sufficient. In this case, you should turn to using PyInstaller directly.

Auto-Py-to-Exe is an excellent choice for implementing small and medium-sized projects, especially when you need to quickly create an application with a graphical interface without having to delve into PyInstaller's settings yourself.

Let's create a console application in Python, and then convert it into an executable EXE file. To do this, write the code and save it in a file named main.py:

This program is designed to reproduce the main menu for entering the application.

To install Auto-Py-to-Exe, you need to enter the following command in the terminal:

To install Auto-Py-to-Exe in Python, you will need to run certain commands. To launch the graphical interface of this tool, just enter the corresponding command in the console:

After that, the Auto-Py-to-Exe graphical interface will appear.

The interface includes three key tabs:

  • Basic settings:
  • Initialization of the original Python script.
  • Definition of the packaging method: one file or one directory.
  • Definition of the interface type: graphical (GUI) or console.
  • Sorry, you have not provided the text for rewriting. Please share the text you want to rework, and I'll be happy to help you.
  • Configuring an icon for your application.
  • Enabling invisible imports.
  • Identifying files and resources that the system depends on.
  • Advanced configuration options:
  • Options for removing temporary files.
  • Characteristics of environment virtualization and PyInstaller's operation.
Screenshot: Auto-Py-to-Exe / Skillbox Media

In the upper right corner, you can select the interface language. Auto-Py-to-Exe supports various languages, including Russian.

Click the "Location" button in the upper right corner and select the Python script you want to convert to an EXE file.

The "Single Folder" mode (—onedir) creates a directory containing both the EXE file and the necessary DLL libraries. The "Single File" mode (—onefile) generates a single executable file. Let's choose the "Single Folder" option.

We're choosing the "Console Application" option because we don't have a graphical interface.

Please proceed to advanced settings.

Screenshot: Auto-Py-to-Exe / Skillbox Media

Specify the application name, enable clean mode, and set the logging level to WARN. The first option will remove all obsolete files created during compilation, while the second will limit console output to only significant warnings about the program's operation.

Look at the "Current Command" panel at the bottom of the Auto-Py-to-Exe main window. All the parameters you specified earlier are automatically added as command-line arguments, as if you entered them manually in the PyInstaller utility.

Screenshot: Auto-Py-to-Exe / Skillbox Media

When all the main settings of our EXE Once the process is complete, click the "Convert .py to .exe" button at the bottom. A directory named "output" will be created in the folder where our Python code is located, containing our EXE file. After that, we can run it.

Screenshot: Auto-Py-to-Exe / Skillbox Media

The executable file prepared using Auto-Py-to-Exe is complete and ready to use.

cx_Freeze — a unique solution for packaging applications

cx_Freeze is a Python library designed for "freezing" scripts for the purpose of converting them into fully-fledged applications. Along with the source code, the package includes an interpreter and all necessary dependencies, allowing you to run the program without first installing Python. This tool is compatible with Windows, macOS, and Linux operating systems.

What's good about it:

  • Programs created with cx_Freeze tend to have faster startup times than EXE files generated using PyInstaller in the "Single File" mode.
  • This library is cross-platform, which allows you to develop applications not only for Windows, but also for various other operating systems.
  • The settings are highly flexible: you can activate or deactivate modules, add images, fonts, and various resources, and customize the functionality of the application's graphical interface, for example, hide the console.
  • The project is in the active support stage: the documentation is constantly updated, and the latest version is compatible with Python up to 3.13.

What's bad:

  • There is no "All in one file" mode, as a result of which instead of a single executable file A folder containing numerous libraries is created.
  • The size of the software folder can increase significantly, especially if the project includes numerous dependencies.
  • Sometimes cx_Freeze does not take into account required modules, especially if they are loaded dynamically or via non-standard import methods. In such cases, they must be added manually.
  • There are potential difficulties associated with system libraries: on Windows, conflicts between DLL versions or licenses may occur, while on Linux and macOS, similar problems may occur with SO or DYLIB.
  • For the program to function correctly, significant manual configuration is required: it is necessary to create an installation script, master the graphical interface, and understand resource paths. While this isn't a difficult task, it can be a bit confusing at first.

Using the Tkinter graphics library, let's create a simple Python script that will use a graphical interface to interact with the console.

Write this code into a file called hello.py.

Now let's install cx_Freeze. The installation process for this tool is similar to the installation process for other programs. To get started, enter the following in the command line:

Now you need to create a special configuration file that will describe the structure of the upcoming EXE package.

This section presents the main characteristics of the upcoming EXE application:

  • name — the name;
  • version — the version;
  • description — a description or explanation of something.
  • Executable files are referred to as "executables".

Let's save this file under the name setup.py in the same folder where your Python script is located.

Launch the console in the current directory and create the executable file with the following command:

As a result, you will have a build folder, which will contain your completed application.

Screenshot: "Windows Explorer" / Skillbox Media

When you run hello.exe, you will see two windows: one console and one with a graphical interface, which will contain a button.

Screenshot: Skillbox Media

If all steps are completed correctly, clicking the button should display a welcome message in the console.

Screenshot: Skillbox Media

With the help of cx_Freeze, a simple EXE application was developed that includes both a console and a graphical interface.

Py2exe is a unique tool for converting Python programs into executable files of the EXE format.

What's in it Pros:

  • Can develop both console applications and applications with a graphical interface.
  • The bundle_files and compressed parameters allow you to adjust the degree of packaging and reduce the file size.
  • With the correct configuration, you can create a single executable EXE file along with the necessary libraries.
  • The latest versions of Python are supported, including 3.13.
  • The project is in an active development stage: updates are regularly released, support for new versions is implemented, and bugs are fixed.

Cons:

  • Available exclusively for the Windows operating system.
  • Even when creating All-in-One builds, there are often external libraries or DLLs that need to be included manually.
  • Dependencies may need to be explicitly specified during setup, especially when using dynamic imports or unusual methods.
  • Compression and packing can slow down the build process and create difficulties during debugging.

Let's create some Python code that will serve as the basis for our future program:

We have developed an interface in which a colored square will be generated when clicking on an empty area with the mouse. Let's save this code in a file called squares.py.

To install Py2exe, use the command line:

Py2exe, like cx_Freeze, requires the user to prepare a configuration file called setup.py, which defines the build parameters. To create an EXE file, often just a few basic settings are enough:

Launch the command line and navigate to the desired folder, then compile our EXE file.

If the process completes successfully, two directories should appear in the source code directory: dist and build. The dist folder contains the finished executable file in EXE format, as well as the DLLs required for its operation. Let's run this EXE file.

Screenshot: Skillbox Media

The EXE file generated by Py2exe is complete and ready to use.

Nuitka: Convert Python Code to Low-Level Machine Code

What's good about it:

  • Nuitka is a compiler that can convert Python scripts to machine code.
  • It includes an interpreter and the necessary libraries along with the code, making installing Python on your computer unnecessary.
  • It is compatible with Windows, macOS, and Linux operating systems.
  • The finished application can run faster than a regular script.
  • The project is in active growth, the documentation is regularly updated, and support covers Python versions up to 3.13.

What's bad:

  • The build process requires more time and resources than cx_Freeze or PyInstaller, since a full compilation is performed in this case.
  • There are many settings, and it may be difficult for a novice user It's difficult to understand all the details at once.
  • The documentation doesn't always provide the answers you need, and as a result, you have to figure some questions out on your own.

Let's create a basic console program using Python:

To install Nuitka using pip on the command line, follow these steps:

Now let's move on to the process of creating an executable file using Nuitka:

Without using the —standalone— argument, Python will generate C files and dynamic libraries in the DLL format. However, if this argument is specified, Nuitka will generate a standalone executable file in EXE format.

Once compilation is complete, a main.dist directory will appear in the project root, containing our finished program with the .exe extension.

Screenshot: "Windows Command Prompt" / Skillbox Media

Choosing the Best Tool for Generating EXE Files

The decision will depend on the result you are trying to achieve.

PyInstaller is ideal for quickly and easily creating EXE files. This tool is compatible with most libraries and comes with high-quality documentation and usage examples. However, it is worth considering that the resulting EXE files can take up a significant amount of memory, and if you select the "single file" option, the program may take longer to launch.

Auto-Py-to-Exe is a tool similar to PyInstaller, but with a much more user-friendly graphical interface. All actions are performed with the mouse: you can select the script, icon, and build mode. However, the program remains fundamentally PyInstaller, so it has the same limitations.

If you need to ensure application compatibility not only with Windows but also with Linux or macOS, cx_Freeze is the optimal choice. This tool supports cross-platform compatibility, but it requires a setup script, which may require additional effort. Because of this, it may be difficult for novice users to master this process.

Py2exe is a utility designed exclusively for the Windows operating system. It was previously quite popular, but its use has become less common. However, it is worth noting that it continues to function.

If the speed of the final application is critical to you, you should consider Nuitka. This is not just a packager, but a full-fledged compiler that converts Python code into C, and then into machine code. The resulting programs do show higher performance, but the build process takes longer and requires more careful tuning.

Learn more exciting information about the code in our Telegram channel. Join us!

Read also:

  • How to learn Python on your own and without spending money: a step-by-step guide.
  • Top 10 Python IDEs: tools for beginners and experienced developers
  • Working with files in Python is an important aspect of programming that allows you to read, write, and manipulate data. First, you need to open a file, which can be done using the built-in `open()` function. It takes two main parameters: the file name and the open mode, which can be, for example, ‘r’ (read), ‘w’ (write), or ‘a’ (appendix).

    After successfully opening a file, you can use methods such as `read()`, `readline()`, or `readlines()` to extract information. If you need to write data, you should use the `write()` method, which will write text to the file. Remember to close the file using the `close()` method to avoid resource leaks.

    There is also the `with` context manager, which simplifies working with files by automatically closing them after completing a block of code. This is especially useful for minimizing potential errors.

    In addition, Python supports working with files in various formats, such as text, CSV, and JSON, which expands its capabilities for data processing.

Python developer specialty with an emphasis on artificial intelligence

Learning Python is entirely possible, even if you have no programming experience. Throughout your training, you will be accompanied by an experienced mentor. You will create three projects that will add to your portfolio, and the Career Center will provide support in your job search as a Python developer.

Learn more