Skip to main content
HomeAbout PythonLearn Python

Two Simple Methods To Convert A Python File To An Exe File

Learn what an executable file is and why it may be useful while looking at how to convert a Python script to an executable using auto-py-to-exe.
Aug 2022  · 6 min read

Python files have two main methods for execution: using the terminal or in a text editor/IDE of your choosing. Note that a Python file is merely a program or script written with Python source code and saved with the .py file extension. There are various scenarios in which you may wish to hide your source code when sharing Python scripts with others. One way to achieve this is by converting your Python file into an executable file. 

In this article, we will cover some of the scenarios that justify converting your Python file to an executable. We will also demonstrate how to convert a Python file to an executable file using two Python libraries: Pyinstaller and auto-py-to-exe. 

Clone this Github repository to follow along with this tutorial. 

Why convert Python to an exe 

Executable files - files saved with the .exe extension - are used to install or run software applications on computers with the windows operating system. The file that allows a windows computer to run an application is the .exe file. 

There are several reasons you may wish to convert a Python program to an executable file. Let’s take a look at a few:  

Malicious activity

Unfortunately, some people on the internet like to spread malicious software to infect other people's devices and steal their information. One way to counter these people is to avoid playing into their scams – this means not blindly downloading or opening .exe files that are not from a reliable source. 

Accessability

Another reason you may wish to convert a Python file to an executable is to share an application with other users. The typical Python program may consist of several dependencies that another user would need to install before the program can run. What if the person does not know how to code? In such scenarios, expecting a user to learn to code before using an application may be unreasonable. Converting a Python file to an executable file allows users to access your program without knowing Python. 

Safeguarding source code

But even if they know who to code, converting a Python file to an executable file may be a good option to prevent your code from being stolen. An executable file prevents code from being stolen because it creates a compiled version of your source code, which makes it harder to comprehend than the actual source code. 

Job scheduling

You may also wish to schedule a job on your computer to execute an .exe file at a specific time. 

Converting Python to exe tutorial 

Now that you know what .exe files are and why you may wish to convert a Python file to a .exe file, let’s look at how to do it in Python. In this section, we will cover two frameworks: pyinstaller and auto-py-to-exe. 

This demonstration will use the New York City Airbnb open data dataset. 

Before data scientists can analyze a dataset, the data must be formatted to be compatible with the tools they are using. Thus, creating a validation schema effectively defines all the validations that apply to each field declaratively. This process can be quite repetitive. To prevent our data scientists from engaging in repetitive tasks, we’ve created an automated validation script to run periodically. 

Note: Be extremely careful when using relative paths if your script must read data. You are better off using absolute paths to ensure your executable works as expected. 

import pandas as pd
from pandas.api.types import CategoricalDtype

def perform_validation(filename:str):
    """
    A function to validate inputs for NYC Airbnb Open data.
    """
    path_to_data = "../.."
    data = pd.read_csv(f"{path_to_data}{filename}")



    # Convert neighbourhood_group to type category
    neighbourhood_group_to_cat = CategoricalDtype(
        categories=["Manhattan", "Brooklyn", "Queens", "Bronx", "Staten Island"],
        ordered=False
        )
 
    data["neighbourhood_group"] = data["neighbourhood_group"].astype(neighbourhood_group_to_cat)

    # Convert room_type to type category
    room_type_to_cat = CategoricalDtype(
        categories=["Entire home/apt", "Private room", "Shared room"],
        ordered=False
    )

    data["room_type"] = data["room_type"].astype(room_type_to_cat)

    # Convert last_review to datetime
    data["last_review"] = pd.to_datetime(data["last_review"])

    # Minimum nights a person can stay is one night
    assert data["minimum_nights"].min() >= 1

    # Minimum number of reviews is 0
    assert data["number_of_reviews"].min() >= 0
 
    # Minimum number of reviews per month
    assert data["reviews_per_month"].min() >= 0.00

    # Minimum amount of listings per host
    assert data["calculated_host_listings_count"].min() >= 1

    # Number of days when listing is available for books
    # Could be 0 if tennant has long term booking
    assert data["availability_365"].min() >= 0

    # Save validated data
    data.to_csv("validated_ab_nyc_2019.csv", index=False)

if __name__ == "__main__":
    # User inputs filename
    filename = input("Enter filename: ")
 
    # Ensure it's a string
    if not filename.isalpha():
        filename = str(filename)
 
    # Automated validation
    perform_validation(filename)

Note: we have copied and pasted this script into the pyinstaller and the auto-py-to-exe directories. 

# Directory structure
|   AB_NYC_2019.csv
|  
+---auto_py_to_exe
|   |   requirements.txt
|   |   validation.py         
+---pyinstaller
    |   requirements.txt
    |   validation.py

Each directory has there own virtual environment in which we’ve installed the requirements: see pyinstaller requirements or auto-py-to-exe requirements. If you’re following along with the code, be sure to create a virtual environment in the pyinstaller directory and auto-py-to-exe directory. 

At a high level, the script above contains a function – learn more about writing functions in Python – that reads in a dataset and then defines the expected format of specific fields in the data. The next step is to convert this Python script into an executable file that could be run periodically to generate a formatted dataset. 

Pyinstaller tutorial

Pyinstaller allows you to quickly convert a Python file to an executable file from your terminal. Once you’ve created your virtual environment and installed the requirements for your script (including pyinstaller), simply open the terminal and navigate to the directory where the Python file you wish to convert is located. 

The next step is to run the following command: 

pyinstaller --onefile validation.py

Initially, you will see several logs of which the final one will say something along the lines of “completed successfully” – given the executable file is created successfully. 

executable file being created

Figure 1: Logs showing the executable file being created and that it is completed successfully.

The completion of this run will create two new directories, build and dist, in the same directory as where the Python file is located. In the dist directory, you will find the validation.exe script.

validation.exe on a dataset

Figure 2: A GIF demonstrating the execution of validation.exe on a dataset.

To run the script, simply click on it. This will bring up a console that asks you to insert the filename of the data on which you wish to run the validation. Once you enter the file's name, the console will close, and the validated data will be created in the same directory as the validation.exe file – see Figure 2. 

Auto py to exe Tutorial 

The first step to creating an executable file using auto-py-to-exe is to run it using the following command: 

auto-py-to-exe 

This should return a graphical user interface (GUI) that will assist us in converting our Python file to an executable file. 

graphical user interface

Figure 3: The graphical user interface returned after running the auto-py-to-exe command. 

Note: if it’s not working, ensure you’ve created a virtual environment in the auto-py-to-exe directory and installed the requirements.txt in your virtual environment using the following command: pip install -r requirements.txt.

The GUI has several fields we must fill in. Let’s take a look at each one and break do: 

  • Specific Location: In this field, you must add the script location of the Python file you wish to convert to an executable.  
  • Onefile: This is where you select whether you wish to create a single directory or file. A single directory will contain all the dependencies required to execute your script and an executable file, whereas selecting “One File” will create a single executable file. 
  • Console Window: The decision between a “Console Based” or “Window Based” console window depends on what is returned by your script. For example, the script we have created above requires a user to input a filename. Thus, the “Console Based” solution is recommended since this will open the console after running the executable file. If there was no need to display the console outputs after running the executable file then “Window Based” is a good option. 

We are also provided with other options to configure the creation of our executable file (i.e. add icons, additional files, and more). In this section, we can also modify the path for where we want to export the files generated by our executable file: to do this, select the “Settings” toggle option and browse to the output directory of your choosing. The last step is to select “Convert .py to .exe” to convert our Python file. 

See the GIF in Figure 4 to see how we configured our executable file. 

Auto py to exe

Figure 4: A GIF demonstrating the configuration for auto-py-to-exe

When we navigate back to the auto-py-to-exe directory, there will be a directory called output: this is where our validation.exe file lives. Select the file to run it, which will bring up a console that asks you to enter a filename:

executable validation file

Figure 5: Console returned from running the executable validation file. 

Simply enter the file's name – in this example, AB_NYC_2019.csv – and press enter. This will close the console and create a new file in the output directory (where the executable file lives) called validated_ab_nyc_2019.csv.

Wrap up

In this article, you have learned: 

  • What a Python file is
  • What an executable file is and why it may be useful 
  • How to convert a Python script to an executable using pyinstaller, which is a great tool for those more comfortable with command line operations. 
  • How to convert a Python script to an executable using auto-py-to-exe, which provides users with a graphical user interface (GUI) to configure how the executable file should be created. 

Learn more about how you could leverage Python to do data science in DataCamps Data Scientists with Python career track.

Topics

Courses for Python

Certification available

Course

Intermediate Python

4 hr
1.1M
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

A Data Science Roadmap for 2024

Do you want to start or grow in the field of data science? This data science roadmap helps you understand and get started in the data science landscape.
Mark Graus's photo

Mark Graus

10 min

Python NaN: 4 Ways to Check for Missing Values in Python

Explore 4 ways to detect NaN values in Python, using NumPy and Pandas. Learn key differences between NaN and None to clean and analyze data efficiently.
Adel Nehme's photo

Adel Nehme

5 min

Seaborn Heatmaps: A Guide to Data Visualization

Learn how to create eye-catching Seaborn heatmaps
Joleen Bothma's photo

Joleen Bothma

9 min

Test-Driven Development in Python: A Beginner's Guide

Dive into test-driven development (TDD) with our comprehensive Python tutorial. Learn how to write robust tests before coding with practical examples.
Amina Edmunds's photo

Amina Edmunds

7 min

Exponents in Python: A Comprehensive Guide for Beginners

Master exponents in Python using various methods, from built-in functions to powerful libraries like NumPy, and leverage them in real-world scenarios to gain a deeper understanding.
Satyam Tripathi's photo

Satyam Tripathi

9 min

Python Linked Lists: Tutorial With Examples

Learn everything you need to know about linked lists: when to use them, their types, and implementation in Python.
Natassha Selvaraj's photo

Natassha Selvaraj

9 min

See MoreSee More