This is a guide on how to build a executable windows file from a Python script. It is especially focused on how to solve the problems that might occur while building a python QT application.

For me, it is important that I easily can distribute my applications and if you give someone who isn’t as geeky as yourself some Python script they most probably won’t know what to do with it. What we instead want to do is to create a executable file that can be run without having Python installed. This can be done with the help of py2exe.
A note for you cool Linux or Mac users out there: This guide only covers windows. Mac users can use py2app and follow guides on aralbalkan.com and tripmeter.in. You badass Linux users can find a guide at omgwtfgames.com. We at popdevelop might post a guide for you later on.
Lets start with the outline of what we need to do to build our executable:

  • Create a Python program
  • Download and install py2exe
  • Create a setup.py script
  • Run the setup.py script
  • Create a Python program

    This shouldn’t be so hard, but since I’m a sucker for GUI applications I will give you two options here. Regardless of the option you choose in this example the scripts should be saved as “main.py”. The first option is to create a simple python script that prints “Hello Executable” in the console. This is done as shown below.

    print "Hello Executable"
    

    The second option is to use a QT GUI Python application. I wrote a guide here on popdevelop on how to do this last week so if you don’t know how to implement a GUI app using QT please follow the Setting up IDE and creating a cross platform QT Python GUI application guide. The code in script we used in that example is shown below and requires that you have installed PyQT.

    from PyQt4 import QtGui
    
    class HelloPython(QtGui.QWidget):
        def __init__(self, parent=None):
            super(HelloPython, self).__init__(parent)
            helloLabel = QtGui.QLabel("Say Hello To PyQT!")
            helloLineEdit = QtGui.QLineEdit()
    
            mainLayout = QtGui.QGridLayout()
            mainLayout.addWidget(helloLabel, 0, 0)
            mainLayout.addWidget(helloLineEdit, 0, 1)
    
            self.setLayout(mainLayout)
            self.setWindowTitle("My Python App")
    
    if __name__ == '__main__':
        import sys
    
        app = QtGui.QApplication(sys.argv)
    
        helloPythonWidget = HelloPython()
        helloPythonWidget.show()
    
        sys.exit(app.exec_())
    

    Choose either of these options and continue to the next step.

    Download and install py2exe

    py2exe is an open source Python extension that allowes you to create executable Windows applications that can run without having Python installed on the computer. Installing py2exe in windows is as easy as installing anything else. Go to py2exe’s sourceforge page to download the installer. Use the one suitable for your Python version. In this guide we use Python 2.6 so we will download the one called “py2exe-0.6.9.win32-py2.6.exe”.
    Execute the installation file. If you have installed Python the installation application should find your python installation and you should have something that looks like the figure below. Don’t you just love that blue color?!

    The lovely py2exe installer


    Step through the installation and py2exe should now be reachable from python. You can check this out by going to the python shell and importing py2exe. This is shown in the figure below.

    Check that py2exe is installed


    If this does not work you should troubleshoot the installation of Python or py2exe. Leave a comment on this post and I will try to help you out!

    Create a setup.py script

    To configure how you want the executable file to behave you will need to create a setup script. If modules are missing or if something goes wrong while creating your executable this is probably where you will fix it. For the first “Hello Executable” option used in this guide we won’t be needing anything fancy. The setup.py should contain the code shown below.

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

    This will create a executable that has a console. To generate the executable go to the folder where your main.py and setup.py file is located and type: “python setup.py py2exe”. This will generate a “build” folder and a “distr” folder. In the distr folder you will find your .exe file.
    If we used this setup.py script for our PyQT script we would get the error below:

    C:\src\dist>main.exe
    Traceback (most recent call last):
    File "main.py", line 1, in
    File "PyQt4\QtCore.pyc", line 12, in
    File "PyQt4\QtCore.pyc", line 10, in __load
    ImportError: No module named sip
    C:\src\dist>

    To fix this we will need to add a couple of things to the setup.py script. Below you see the script that solves the ImportError problems.

    from distutils.core import setup
    import py2exe
    
    setup(windows=['main.py'], options={"py2exe": {"includes": ["sip", "PyQt4.QtGui"]}})
    

    The first thing you might notice is that we changed “console” to “windows” in the setup call. What this does is that it runs a windows application with no console. Then the options parameter has been added making py2exe import Sip, which it complained about earlier and PyQt4.QtGui. The QtGui import is there because for some reason the application will not import PyQt4.QtCore from QtGui when py2exe has built it.

    Conclution

    This guide shows you how to build an executable out of a python script. py2exe does this job well and after a couple of tweaks it will also build your PyQT application. If you have any problems while following this guide please leave a comment and I will try to fix it for you.

    Further reading

    Now that you’ve got your setup script and built your exe there might be some energy left in you so here’s a couple of sites that you might want to visit.

    The peeps over at bytes.com has gotten their hands on some master setup.py file that should do everything for you. Read more…

    eHow has a guide much like this one but a bit simpler. Read more…

    Stackoverflow.com is an amazing site and there is of course a thread there where people are discussing alternatives to py2exe. Read more…

    There is a thread over at devshed discussing py2exe. It’s dated but has lived from 2004 to 2009. Read more…

    Update Jul 5, 2010

    I found this guide at arstechnica.com named How-to: Deploying PyQt applications on Windows and Mac OS X. It also shows how to build a Mac version of your PyQt Python script.


    • http://popdevelop.com Johan Brissmyr

      Really nice work there Mike! I never managed to get my OS X app running from a Python project. The problem was loads of external dependencies, libraries and such. Perhaps I’ll write a similar article when getting that stuff runing

    • http://mikaelhalen.com Mikael Halén

      Thanks Johan! Most of the external dependencies solved themselves for me in my python twitter client. Some tweaks were needed, like when I downloaded images and wanted to set them to QLabels it wouldn’t support jpeg for some damned reason. It ended with that I converted all the jpegs to png. It was a dirty but quick solution that has worked fine for me. I might show that solution here later on. Even if it isn’t pretty!

    • kieu pham

      I can’t thank you enough. Just when I was about to abandon the effort of converting my Python Qt script into exe, when one trouble comes after another. Found your example, and saw all my troubles explained here. I have me exe built and run successfully in few minutes following your guide. THANK YOU!

    • http://mikaelhalen.com Mikael Halén

      Thank you! I’m glad you liked it! Python and QT is such a nice combination!

    • http://happyrain.org/ Emily

      Really nice work there Mike! I never managed to get my OS X app running from a Python project. The problem was loads of external dependencies, libraries and such. Perhaps I’ll write a similar article when getting that stuff runing

    • http://www.markzonder.com/ Amy

      I can’t thank you enough. Just when I was about to abandon the effort of converting my Python Qt script into exe, when one trouble comes after another. Found your example, and saw all my troubles explained here. I have me exe built and run successfully in few minutes following your guide. THANK YOU!

    • http://mikaelhalen.com Mikael Halén

      Thank you Emily! I never came so far as to build my application for OS X but I would like to try it out. It would be really nice to read your article if you wrote one!

    • Mayowa

      Thanks man!. Just what i needed to deploy my apps.

    • http://mikaelhalen.com Mikael Halén

      You’re welcome! Good luck deploying!

    • Chris

      Worked like a charm. Only received one error when I executed my .exe and it was because I forgot to include a data_file in the setup.py. You might want to mention about the Visual C .dll’s that py2exe doesn’t typically include. Great write up, thanks for taking the time to post it!

    • http://mikaelhalen.com Mikael Halén

      Hi Chris,

      thanks for leaving a comment. It is great to hear that this article can be of assistance.

      I can’t remember what’s up with those Visual C .dll’s. What did you need to do to include those?

      Thanks
      Mike

    • http://31shebang.wordpress.com Viranch Mehta

      Hi,

      I’m trying to deploy a Python2.7 / PyQt-Py2.7-4.8 with py2exe-0.6.9-py2.7

      I followed the steps, it does not give the “sip” error (no complain) but spits out that “MSVCP90.dll not found”

      I’m lost as to how to fix that. Any help would be appreciated. :)

      Viranch

    • Kaushik Shrestha

      Hi,
      I’m trying to deploy a Python2.7 / PyQt-Py2.7-4.8 with py2exe-0.6.9-py2.7
      I followed the steps but it gives following error :
      QtCore4.dll : No such file or directory

    • Anonymous

      This is why I prefer Ubuntu. Software deployment (other than .NET) on Windows is pure hell.

    • Rasool12

      An easy way to convert Python files to EXE file use htwoo

      download link :

      http://sourceforge.net/projects/htwoo/files/

       

    • Fábio

      Hi , i`m a brasiliam and, I dont know speak english but i ll try.
      I m having problems with my project, I need import tho module
      “mixer” from pygame, it is my problem, i dont get it in my build. can u help me?