devxlogo

Create Python Executables Automatically

Create Python Executables Automatically

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.

  1. First create a Python script.
  2. Create a setup file that includes the name of your setup and also the name of the file whose executable you want to create.
  3. Run your Python script from the command line, for example, python yourFile.py py2exe.
  4. 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.


You need to extract the file name (minus the extension) from the file path that the user has specified. The code below assigns that file name to variable package, which you need to create the setup file. For example, if the specified file path is python/somePyFile.py, then at the end of the code fragment, package will hold the value somePyFile.

   package = re.split(":",fileName)   package = re.split("/",package[len(package) - 1])   package = re.split(".py",package[len(package) - 1])   package = package[0]

The next task is to write a setup file containing the commands required to create the executable. The code asks the user for the name of the setup file. If the user simply presses the Enter key, the setup file name defaults to setup.py.

  def getSetupName():      global setupName      setupName = raw_input("Enter name of setup file (or  for default): ")      if(setupName == ''):         setupName = "setup.py"      try:         fp = open(setupName)         fp.close()         flag = raw_input("Setup file exists! Rewrite (0=no; else )? ")         if(flag == "1"):            getSetupName()      except IOError:         setupName = setupName   getSetupName()

The following code writes that information into the setup file. If the file does not exist, the code creates it. If the file exists, the code asks the user to confirm that it should overwrite the file.

   fp = open(setupName,"w")   temp = """from distutils.core import setup   import py2exe   setup(name = "%s",      scripts = ["%s"],      )""" % (package,fileName)

For example, if a user enters the file path python/fader.py, the variable package gets set to fader, and then the setup.py file will contain the following text:

   from distutils.core import setup    import py2exe    setup(name="fader",         scripts=["python/fader.py"],    )

Note that the above data remains in the file only during this stage.

You could run the setup.py file manually, but it’s much more convenient to automate that as well. To do that, you need to be able to add py2exe to the command-line for the setup.py file, and then launch it.

You can manipulate the command-line via the Python globals() dictionary, which contains information about a number of objects, among which is the sys object. The sys object exposes the argv list, which contains the list of command-line arguments. Using the sys.argv list, you can manipulate (and modify) command-line arguments. The following line appends py2exe to the command-line arguments list; that command-line argument is required to successfully create an executable.

   sys.argv.append("py2exe")

To create the executable, you dynamically execute the file setup.py created earlier using Python’s execfile() method.

   execfile(setupName)

The execfile(fileName) method basically performs the following steps:

   fp = open(fileName,'r')   exec f   f.close()

Calling the execfile() method is equivalent to the preceding three sequential steps; in other words, executing setup.py programmatically is equivalent to running the file setup.py from the command-line with a command-line argument of py2exe, for example:

   D:python22>python setup.py py2exe

Finally, the last lines in Listing 1 clear the file setup.py. Thus, after the script executes, setup.py becomes a blank file, ready for the next cycle.

When you run py2exe it creates the output executable in the /dist/ directory.

Save Yourself Some Time
Without using makeExe.py, assuming you already have a setup file template ready, you will first need to edit the file, add the required information, and then save it. Next, you must go to the command line and then type the string to create the executable. But using makeExe.py, you just need to double-click on it and then enter the file path for the Python file from which you want to make an executable, and it creates the executable and saves it for you. Without any doubt, the latter task is less far irksome and time-consuming, particularly when you need to create a number of Python executables.

Future Work
This article explains the underlying technique involved in automating the creation of Python executables. Enhancements in the form of a graphical user interface, using Tk or wxPython, would be desirable, as would batch creation of executables.

A Windows Batch File to Automate the creation of Python Executables
As you’ve seen, the process of creating a Python executable is simple enough, but it could be simpler. If you use py2exe directly, every time you want to create an executable you must first create a new setup file or edit an existing setup file. The py2exe process simplifies things somewhat, but you can make the process even simpler.

You can integrate the setup steps using a simple DOS Batch file. The makeExe.bat file is a simple DOS batch file. The batch file makes use of two other files that I call configuration files. These files are simply called 1.txt and 2.txt. You place them in a directory named config. Note that all these files must be present in your Python root directory (the directory where your main Python binary exists), typically a folder such as C:Python22, which is the folder that the following discussion assume is your directory name. Figure 2 shows how your directory structure should look:

Figure 2. Directory Structure: The figure shows the directory structure you need to set up for the makeExe.bat file to work properly.

If you look at the two text files, you’ll see they couldn’t be simpler:

config/1.txt

   set fileName=

config/2.txt

   set dirName=

You’ll see how these files are used later. Here’s the content of the makeExe.bat batch file.

   0 rem Batch file to automate creation of Python       executables...   1 rem ...using py2exe       (http://starship.python.net/crew/theller/py2exe/)   2 rem by Premshree Pillai (http://www.qiksearch.com/)   3 @echo off   4 echo (After each input press return, ^z and return again)   5 echo Enter the file name whose executable you want to       create:   6 echo (...use relative or absolute path)   7 copy config1.txt + con config	emp1.bat   8 echo Enter the setup name to be created:   9 echo (...should be same as file name, without the       extension of course!)   10 copy config2.txt + con config	emp2.bat   11 call config	emp1.bat   12 del config	emp1.bat   13 call config	emp2.bat   14 del config	emp2.bat   15 echo from distutils.core import setup > configset.py   16 echo import py2exe >> configset.py   17 echo setup(name="%dirName%", >> configset.py   18 echo      scripts=["%fileName%"], >> configset.py   19 echo ) >> configset.py   20 python configset.py py2exe -w   21 del configset.py   22 echo The executable has been created in dist\%dirName%

Author’s Note: The line numbers in the preceding listing exist for explanation only and are not part of the code.

How MakeExe.bat Works
The following explanation walks through the lines of the makeExe.bat file, giving a bit of explanation about each one.

  • It uses the COPY CON (copy from the keyboard console) command to get user input.
  • Lines 5-6: When you run the makeExe.bat file, it prompts you for the name of the Python script whose executable you want to create. You may enter the file name using a relative or an absolute path. Now press Enter, [Ctrl z] and then press Enter again.
  • Line 7: The batch file appends the name you entered to the 1.txt file and saves that as a new file named temp1.bat. For example, if you entered myScripts/myFile.py, the temp1.bat file would look like this:
   set fileName=myScripts/myFile.py

  • Lines 8-9: Next, the file prompts you to enter the setup file. Enter the name of your Python script, but without the .py extension. For example, if your file name is urn.py, just enter urn. Now press Enter, [Ctrl z] and then press Enter again.
  • Line 10: The batch file appends whatever you entered to the 2.txt file and writes the result to a new file called temp2.bat. For example, if you entered myFile (which would be the case if your file name is myFile.py), the temp2.bat file would look like this:
   set dirName=myFile

  • Lines 11-14: The batch process calls each of the newly created batch files, (temp1.bat and temp2.bat) using the call command. This sets the two environment variables %fileName% and %dirName%, after which it deletes the two batch files using the del command.
  • Now, the main batch process uses the file and directory names that the user entered by making use of the %fileName% and %dirName% variables respectively.
  • Lines 15-19: These lines create the temporary setup file, set.py, using the user-entered values.
  • Line 20: This line runs the newly created setup file, set.py using Python. Note that the -w switch is used to create Windows applications without the DOS window popping up.
  • Line 21: This line deletes the set.py file.

Note that the batch process creates all temporary files in the /config directory, and that py2exe creates the executable in the /dist/ directory (see Figure 3).

Figure 3. MakeExe.bat In Action: The figure shows an interactive session of the batch file with sample user input.

I hope this simple batch file makes things a wee bit easier. If you have suggestions for improvements, feel free to email me with them.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist

©2024 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.