Skip navigation.

Compiling Python Scripts to Windows Executables

Compiling Python Scripts to Windows Executables

I often write quick Python scripts that I need to run on other machines. It is sometimes easier to just drop a windows .EXE onto a machine (with a Python Interpreter compiled into it), rather than doing a full Python installation. To do this, I use py2exe

py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs. This enables your Python scripts to be run on Windows platforms without a Python installation.

You can run py2exe directly from the command line, or you can script it. I wrote a small convenience script that I use for general compilation.

Let's call the compilation script: compile.py
Let's say we have a script we want to compile named: foo.py

You would then invoke it from the command line like this:

>python compile.py foo.py

This will create a 'dist' subdirectory containing the newly created executable along with some necessary DLL's.


Here is the code I use for my compile.py:


#!/usr/bin/env python
# Corey Goldberg


from distutils.core import setup
import py2exe
import sys


if len(sys.argv) == 2:
    entry_point = sys.argv[1]
    sys.argv.pop()
    sys.argv.append('py2exe')
    sys.argv.append('-q')
else:
    print 'usage: compile.py <python_script>\n'
    raw_input("press ENTER to exit...")
    sys.exit(1)


opts = {
    'py2exe': {
        'compressed': 1,
        'optimize': 2,
        'ascii': 1,
        'bundle_files': 1
    }
}


setup(options=opts, zipfile=None)



(note: you need to have Python and py2exe installed on a Windows box to run this)