
his article shows you how to automate the task of creating Python executables via
py2exe using Python itself. I call the Python file containing the code
makeExe.py. This technique requires only one file,
makeExe.py; it creates all other necessary files at run-time. First, a short review on the process of creating a Python executable using
py2exe.
Creating a Python Executable
| Editor's Note: The author recently submitted another method for creating Python executables using a batch file, along with an explanation of how to use it. This new method has been added as the last page of this article, at his request.. |
The following four steps describe the process required to create a Python executable.
- First create a Python script.
- Create a setup file that includes the name of your setup and also the name of the file whose executable you want to create.
- Run your Python script from the command line, for example, python yourFile.py py2exe.
- Creating a new setup file or modifying an existing one each time you need to create an executable is onerous. Wouldn't it be better to have these steps integrated into one? That's exactly what the Python sample code for this article, makeExe.py does.
| Author's Note: You can get py2exe here. You'll also find the full instructions for using py2exe via that link. |
How the makeExe.py File Works
Listing 1 contains the full contents of the
makeExe.py file. When you run this file (you should run it from the Python root directory), it asks the user for a file name, then creates an executable for the specified file (see
Figure 1). The short code excerpts that follow explain how the code works.
 | |
| Figure 1. A Simple UI: The makeExe.py file running in a command window requests a file path to the file for which the user wants to create an executable. |
First, the code imports the modules
sys and
re. You need the
sys module to manipulate the command-line arguments, and the re module to extract the filename (without the
.py extension) from the file path entered by the user.
import sys
import re
Next, it asks the user for the file name from which to create the executable. The code accepts relative file paths as well as full file names. The code also ensures that the specified file exists.
def getFileName():
global fileName
fileName = raw_input(
"Enter file name (rel or abs path, eg.,
python/file.py): ")
try:
fp = open(fileName)
fp.close()
except IOError:
print "File does not exist!"
getFileName()
getFileName()