Simple Python Distribution Tutorial

I want to be able to send someone a package containing a Python script and the bare minimum for them to run that script on Windows. In Perl, this is quite easy, I believe you can just send your script with perl.exe. This is how I did it in Python.

I’m assuming you already have Python installed. I did this on Python 2.5. You may need to make some changes for other version of Python. My starting point was the tutorial on the py2exe website.

Install py2exe and create hello.py:

python setup.py py2exe

Create a script to run hello.py, call it exec_hello.py:

import runpy
import sys
import os

sys.path += [os.path.dirname(sys.argv[0])]
runpy.run_module('hello.py')

Create a setup.py script:

from distutils.core import setup
import py2exe
setup(console=['exec_hello.py'])

Run this at the command prompt to generate the distribution:

python setup.py py2exe

Copy hello.py into the dist directory.

You should now be able to run dist/exec_hello.exe at the command prompt and it will call hello.py.

I tided things up by getting the setup script to remove unnecessary files and to copy in the hello.py script. It also renames exec_hello.exe to hello.exe:

import os
import shutil
from distutils.core import setup
import py2exe

setup(console=['exec_hello.py'])
os.remove('dist/bz2.pyd')
os.remove('dist/unicodedata.pyd')
os.remove('dist/w9xpopen.exe')
shutil.rmtree('build')
shutil.copy('hello.py', 'dist')
shutil.move('dist/exec_hello.exe', 'dist/hello.exe')