Your browser does not support JavaScript!
Upvotes Anonymous 6 User 0

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:
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:
Open the directory containing the files and run (double-click) the batch file:
Running it:
There are warnings, but the warnings above can be ignored in our case.

Now you should see a dist directory:
Inside the dist directory is an executable:
Running the executable from the command prompt:
We get our result! 

If you'd like, you can download the project here:
Was this helpful?

Comments

Byanonymous Anonymous 0 User 0
You might add a note explaining that PyCharm doesn't come with 'Calc' installed.  So in the build_exe.py file, it appears with a red squiggly underline, reporting that 'calc' was not found. 

The solution is to click the red underline to get the red lightbulb, open this light bulb's drop-down menu and select the second option, which is "Install the Calc Package".

After Calc installs (and after retyping the line "from calc import add") the red warning lines vanished.
Byanonymous Anonymous 0 User 0
Here's a change to your instructions needed for those making GUI programs:

In the line:
setup(console=['my_GUI_program.py'])the word "console" needs to be changed the word "windows", making the line read:setup(windows=['my_GUI_program.py'])
Otherwise, an ugly black console window peers out from behind the GUI .exe program every time you start it.
Byanonymous Anonymous 0 User 0
When you download the .zip file and open the contents in PyCharm, you get red squigglies for the 'calc' package? (It's a package included with the code, so that shouldn't happen).
Byanonymous Anonymous 0 User 0
Didn't work for me. Current error is: Fatal Python error: Py_Initialize: unable to load the file system codec ImportError: No module named 'encodings' I'm trying to do a standalone program to do bulk filename change on xml file sets for Windows 10 in Spanish.

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License