How to Create an Executable from Python 3 Code using py2exe

First, install py2exe.

Let's build an executable for a sample Python project. We have an addnumbers.py:

addnumbers.py

that references another module to help add two numbers.

Let's create a Python file (based on this example) to help build the executable:

from distutils.core import setup
import py2exe
from calc import add

setup(console=['addnumbers.py'])

Note that we needed to import the add module from our calc package.

I usually create a batch file (build_exe.bat) to run the Python script:

python build_exe.py py2exe
pause

In PyCharm I now see the files:

build_exe.bat and build_exe.py now exist

Open the directory containing the files and run (double-click) the batch file:

double click the .bat file

Running it:

running python build_exe.py py2exe

There are warnings, but the warnings above can be ignored in our case.

Now you should see a dist directory:

dist directory exists now

Inside the dist directory is an executable:

addnumbers.exe now exists

Running the executable from the command prompt:

running addnumbers.exe

We get our result!

If you'd like, you can download the project here.

Comments

August 18, 2022 19:08

Super helpful, thank you!

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.