The result here will be to convert a simple python app into a single .exe file that can be copied and run on any Windows XP machine. It may work on many other Windows platforms, but I haven't tested it.
You'll need a working Python installation first, preferably v2.3 or later. If you haven't installed py2exe yet, or if you have, but you're having problems, I suggest that you start with one of the py2exe self-installing files available for these versions, which put everything where it needs to be. If you need to use the .zip for some reason (older Python, etc.), I can't help much, because that's where I had my initial difficulties.
You can get py2exe at this SourceForge link. Click on the Download link, and choose the package from the list that matches your Python installation.
Finally, create yourself a new directory somewhere to store the following files so they can stay together until you're comfortable manipulating them.
Let's start with a basic Hello World app:
Expand|Select|Wrap|Line Numbers
- #!/usr/bin/env python
- for i in xrange(10000):
- print "Hello, World!"
Run it by double-clicking on it to make sure it works, i.e. that your Python path is setup correctly and so forth.
Now, create a python setup app, again with your choice of editor, and save it as setup.py:
Expand|Select|Wrap|Line Numbers
- #!/usr/bin/env python
- from distutils.core import setup
- import py2exe
- setup(
- console=["HelloWorld.py"],
- zipfile=None
- )
Expand|Select|Wrap|Line Numbers
- python setup.py py2exe --bundle 1
At this point, you should have three files, HelloWorld.py, setup.py, and setup.bat, all in the same directory.
Double-click on setup.bat and watch the fireworks. Depending on your hardware, it could take from a couple seconds to a minute to complete.
When the cmd window closes, check the directory where you stored the three files. You should see two new directories. The build directory is just tempfiles used by setup, and can be deleted. The dist directory contains the grail, Helloworld.exe, plus a couple other files you shouldn't need (py2exe isn't perfect, yet).
Open dist, double-click on HelloWorld.exe, and you're in business. Copy HelloWorld.exe to another computer (without Python on it), and run it there. Voila.
A few notes:
py2exe just converted your 4k .py file into a 3.23MB .exe file, because it bundled a python interpreter, any required DLLs (few or none, in this case), and any referenced libraries (same) into this file, and it'll do so for every .exe you create.
The specific options I supplied in setup.py and setup.bat are there to cause py2exe to create a single file executable. By default, it creates multiple files in the dist directory, all of which must be copied together to another machine to ensure it will execute. There are reasons why this might be desirable, but they're beyond my reach to discuss at this point.
Visit www.py2exe.org to explore additional options.
Cheers,
- Mark