Converting.py files to.exe is a more common process than you would think. Consider the following scenario: you’ve just finished writing an excellent Python program and want to share it with the rest of the world. You give a friend a directory containing all of your scripts and instruct him to try them out. He’ll need to install Python first and then run the program from the command line or the IDE shell. “Command line?” your friend scoffs. Oh no, that’s not my cup of tea.”
Perhaps you’re an administrator who needs to get everyone in the company to run your Python script. Yes, this includes all non-technical people. So how do you get your Python code to users who expect to run it by simply clicking on an executable file?
Every day, we generate many Python applications that we wish to share with the rest of the world. It’s not like you’ll hand out that Python application to everyone and have them execute it in an IDLE shell. However, you want everyone to be able to run your Python script without having to install Python. As a result, you can convert the .py file to a .exe file for this project.
Compiling Python to exe
Fortunately, several Python utilities can help you convert .py files to .exe files. They’ll “freeze” the code and transform it into an executable file. We’ll look at cx_Freeze, PyInstaller, and Auto PY to EXE, three of the most common choices. All of these tools are flexible and simple to use, but you can prefer one over the other depending on your needs.
Python is a must prerequisite. So, continue reading if you haven’t already. But, on the off chance that Python is installed and enabled, you can skip this section.
How to Use the ActiveState Platform to Install Python Packages
Choose Python and the operating system you’re using from the Get Started menu. Then, simply download the activatePython tool and use it to install your runtime once it’s finished. Next, select the required packages for this tutorial, such as cx freeze and PyInstaller.
That’s all there is to it! Python has now been installed in a virtual world.
The alternative is to download Python from python.org as shown below using the following link and follow the installation wizard.
Installing and setting up Pyinstaller
Step 1: Make sure Python is on the Windows path
First, download a recent version of Python and then tick the option to ‘Add Python to PATH. ‘ This is a simple way to add Python to the path:
Step 2: Open the Command Prompt in Windows
Then, launch the Windows Command Prompt as follows:
Step 3: Install the Pyinstaller Package. To install the pyinstaller package, execute the following command in the Windows Command Prompt (and then press Enter):
pip install pyinstaller
Now you are ready to start converting your .py to .exe
How to convert a .py file to a .exe file
To build our Executable, we’ll need a Python program. For this example, we’ll be using concentric_circles.py, a simple script that prints out concentric circles.
#concentric_circles.py # program to draw concentric circles import turtle as tut tut.penup() for k in range(1, 500, 50): tut.right(90) # Southward facing tut.forward(k) # Move by a single radius tut.right(270) # move to begin heading tut.pendown() # place back the pen down tut.circle(k) # circle drawing tut.penup() # while going home, Pen up tut.home() # start position
If you’re using a machine with a windows operating system, all you have to do to create a .exe file from concentric_circles.py by following these steps:
- Open the command line.
- Go to the folder where the concentric_circles.py program is located.
- Then run pyinstaller concentric_circles.py as shown below.
The result is the creation of a folder called “dist” in the folder containing your Python code, and the concentric_circles.exe file is located in that folder, as shown below.
When you double click on the file, concentric_circles.exe, the program will create concentric circles as shown below.
cx_Freeze generates standalone executables from Python scripts at the same speed, is cross-platform, and should run on any platform that Python supports. The standard features in the current version of cx_Freeze include:
- Importlib.machinery is used in the new ModuleFinder.
- Package metadata is supported.
- Support for Python 3.8 has been improved, and experimental support for Python 3.9 has been added.
- MSYS2 and Anaconda are both supported.
- Multiprocessing enhancements
- The detection and dissemination of libraries have been improved.
- setuptools and importlib.metadata have been integrated.
- Hooks that are new or enhanced
- Modernization of the code
- Various bugs have been fixed.
How to Install cx-Freeze
Install cx_Freeze by running the following command on the command line interface
pip install cx-Freeze
With cx_Freeze, the process is almost as quick, but there is an additional configuration stage. You must first build a file called “setup.py” in the same folder as the concentric_circles.py program before running cx_Freeze. The setup.py file configures cx_Freeze’s options, and it can get complicated if you’re trying to do anything specific. However, in this case, it’s pretty straightforward:
# setup.py from cx_Freeze import setup, Executable setup(name = "concentric_circles" , version = "0.1" , description = "" , executables = [Executable("concentric_circles.py")])
Locate the concentric_circles.py and setup.py files in the convert folder. Then, run the Python setup.py build command.
Python setup.py build
The .exe file resulting after running the above command will be available nested in /convert/build/exe.win-amd64-3.9.
Configurability vs. Simplicity
Although the setup file needed by cx_Freeze adds a phase to the method, it also gives you many options. For example, you may define the modules, directories, and packages to include (or exclude) from the construct in the setup file. In addition, it would help if you gave your executable a target name and a path to the icon used to display it. Finally, during installation, you can also choose to set specific environment variables. All of this aids you in delivering an executable that precisely meets your requirements.
PyInstaller, on the other hand, takes the approach of allowing you to freeze your code without having to think about all the choices. It comes with most libraries pre-installed, so you don’t have to worry about including them later. PyInstaller is everything you need for the most popular use cases. It’s much more difficult to define these conditions in PyInstaller if you have anything like secret imports to deal with.
Compatibility Across Platforms
Both cx_Freeze and PyInstaller are cross-platform, meaning they can run on any operating system. Neither of them, however, can cross-compile. You’ll not be able to generate .exe files if you use a Mac or Linux. To deliver your software to users through various platforms, you’ll need to create it on a variety of platforms. That is, you will have to compile on windows when a section of users run windows PC, compile on mac for mac users, and Linux for Linux users.
Obfuscation of the code
In the quest to build a distribution that is independent of your source code, use both cx_Freeze and PyInstaller. Both, however, contain Python scripts that have been compiled (.pyc files). These could theoretically be decompiled to expose the code’s logic. In addition, it would help if you encrypted the bytecode of your app to prevent it from being reverse-engineered.
PyInstaller has a command-line option to encrypt the bytecode using the Advanced Encryption Standard, AES256. To achieve the same result with cx_Freeze, you’ll need to install a third-party tool like pyarmor or pyobfuscate.
Single file Mode
This procedure aims to make things easier for your application’s users. But what could be simpler than handing them a single executable file to open? PyInstaller allows you to collapse a directory into a single file, but cx_Freeze does not. So, PyInstaller is the clear option if your end-users won’t be happy without the push-button convenience of a single.exe file.
- Simple to use; no setup needed
- Code obfuscation built-in
- Can reduce directory to a single executable
- Customization is more difficult
- Cross-compilation is not possible
- Highly configurable
- Easy to include or remove libraries directly
- Ability to set environment variables during installation
- It is more difficult to use
- Incompatible with cross-compilation
- Must be distributed as part of a more comprehensive directory
PyInstaller will operate right out of the box for applications that use the most popular libraries and deliver the executable you need. In most instances, its simplicity, combined with some beneficial features, makes it an excellent first choice. However, if the source code needs more careful configuration, cx_Freeze gives you more options and precise control when converting .py to.exe.
Both tools are simple to use and convert your Python code into an executable file that you can share. The choice is yours as to when the app is ready for delivery.
Auto PY to EXE
Auto PY to EXE is a fantastic program for creating.exe files from your Python projects, whether they are single .py files or a set of them.
Where do I begin?
Installing PyPI is the first step. Run the following command in cmd to install the application:
pip install auto-py-to-exe
Run the following command in the terminal to start the application:
Note: A similar installation process is available from the main page, which can be accessed by following this link.
You have a few critical choices to choose from as follows:
- Choose your.py file.
- Choose between “One Directory” and “One File.”
- Additional files may also be selected.
- Select your.py file
Choose one of the files that begin the program if you have more than one.
- Choose “One Directory.”
It’s pretty straightforward. When the “One Directory” option is selected, “Auto PY to EXE” will combine all dependencies into a single folder. Then, in the “Advanced” menu, select the Output directory. If you placed media files/folders in the Output directory, you shouldn’t have any problems using them within your.exe.
- Choice “One File.”
When the “One File” option is selected, “Auto PY to EXE” creates a single.exe file with all dependencies but no media files. It is OK if your software only has a standard Windows interface with no icons, backgrounds, or media folders, or if you’re OK with putting the media folder in the same directory as the.exe file. In fact, the rest of this section is optional.
- Select additional documents
“Auto PY to EXE” has a menu called “Additional Files” that allows you to add files of your choosing. However, there is a catch. “Auto PY to EXE” makes use of pyinstaller, which unpacks the data into a temporary folder and saves the path to that folder in the _MEIPASS environment variable. Your project will not locate the required files because the path has changed, and it will not recognize the new path. To put it another way, if the option “One File” is selected, the files selected from the “Additional Files” menu will not be added to the.exe file. To get around this, use the code given below by the Auto PY to the EXE developer.
def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path)
Replace the connection to the media file you have now with this code to use in your project.
Consider the following scenario:
The relation will now be correctly referenced, and the selected files will be successfully packed into a .exe file. As an example:
Before, there may have been a connection.
After that, the resultant link is
Select CONVERT PY TO. EXE
5: Put your software to the test!
All is now over! It should be run. Put it to the test. Take a look at what’s going on. Make sure everything is working in order.
You created one directory. Thus, it would help if you kept all of your files in a single directory.
If you created a single file, the result is a single.exe file. If you had a need and followed the steps correctly, your.exe file would be filled with all media. There are no media files or directories that must be present with the.exe file to view them correctly.
When done, you will be provided with the following options.
When you select the option ‘Open Output Folder,’ the results will appear as follows.
Subsequently, proceed to open the concentric_circles directory, and you get the following view.
Here, you can run the application by double-clicking on concentric_circles.exe
Example how to use pyinstaller
First, you must save your Python script to the location you wish.
We will use the following Python script to display ‘Hello World!’ when you press the button for demonstration purposes:
import tkinter as tk main= tk.Tk() h_canvas = tk.Canvas(main, width = 300, height = 300) h_canvas.pack() def helloUnderscored (): h_label = tk.Label(main, text= 'Hello Underscored', fg='red', font=('helvetica', 12, 'bold')) h_canvas.create_window(150, 200, window=h_label) h_button = tk.Button(text='Click Now',command=helloUnderscored , bg='grey',fg='white') h_canvas.create_window(150, 150, window=h_button) main.mainloop()
The Python program was given the moniker ‘ helloUnderscored.py’
Step 5: Using Pyinstaller, create the executable
Using pyinstaller, you can now produce an executable from a Python script.
To do so, open the Command Prompt and type cd, then the directory where your Python script is kept
In our case, we used the command prompt to type the following:
Create the Executable using the following template:
pyinstaller --onefile pythonScriptName.py
Because the pythonScriptName in our example is helloUnderscored,’ the command to produce the Executable is:
pyinstaller --onefile helloUnderscored.py
Step 6: Execute the Script
Your Executable should now be produced at the given location.
In our situation, we returned to the location where the helloUnderscored script was first saved (C:\Users\tuts\OneDrive\Desktop\convert>). At that place, a few more files were created. Open the ‘dist’ folder to find the executable file, as shown below.
You should run your application after clicking on the file (if you get an error message, you may need to install Visual C++ Redistributable).
If you click on the ‘helloUnderscored’ executable in our example, you’ll see the following display with a single button:
Frequently Asked Questions
What is the best way to convert Python to.exe?
You can convert Python to.exe files with cx_Freeze , Auto PY to EXE, or PyInstaller to make it easier to run Python scripts on any platform. PyInstaller is easier to use and, in most situations, a decent first option. cx_Freeze, on the other hand, has more advanced configurations.
Is Python capable of converting files to.exe on its own?
No, Python automatically generates.py files. There is no way to create.exe files in the Python standard libraries. To convert your application from .py to .exe files, you can use a third-party library like cx_Freeze, Auto PY to EXE or PyInstaller.
Alternatively, having an account with the ActiveState Platform allows you to customize a Python runtime environment with standard and third-party libraries/packages.
How do I make a Windows Python.exe file?
Suppose you’re using Python and want to build an executable that your Windows users can run with a single double-click, use cx_Freeze or PyInstaller to convert your Python code to a .exe file. cx_Freeze allows you to set environment variables during installation, while PyInstaller will enable you to freeze your code without thinking about all the options.
Is it possible to run a .py file without first converting it to an.exe?
No, .py files cannot be double-clicked. Instead, they have to be run, which entails loading into a Python interpreter. Thus, there is a need to use Auto PY to EXE, PyInstaller or cx_Freeze if you’re running Windows and want an easier way to run Python programs – by double-clicking.
In this article, we have looked at converting your .py files to .exe for easy execution. The three approaches we have examined include PyInstaller, cx_Freeze, and Auto PY to EXE. Each of them has its advantages and disadvantages. We hope by following this article, your task of converting .py to .exe has been dramatically simplified.