• Sponsored Links

Packaging a python .py program into an Exe

Share this :

Packaging a python .py program into an Exe

I am writing this post to explain how to create a python script into a windows executable file . Any python script ends in .py extension and executes on any OS say it be Linux,Mac or Windows wherever you have OS Specific python installed but problem comes when we want to distribute this program to other people who may not have python installed on their Laptops or Computers .This is more specific when we talk about GUI based programs in python .

Very easy and convenient way for anyone to distribute a program over internet is via a .exe file and I with the help of this blog will try to explain how to create a .py python program into a windows executable program .

  1. Install Python on your development environment and create your python program which ends with .py
  2. Download and install py2exe in your machine and create a .exe generated code from it
  3. Create a single .exe installer from the .exe and other files created in step 2.

 

Below i am going to explain each of these steps .

Step1 Install Python on your development environment and create your python program which ends with .py :

Below is a minimal  python code to create a small window with the help of python 2.7 .

import sys
from PyQt4 import QtGui,QtCore


class SimpleWindow(QtGui.QMainWindow):
    def __init__(self):
        super(SimpleWindow, self).__init__()
        self.UI()


    def UI(self):
        print "Hi"
        self.setWindowTitle("Simple Window")
        self.resize(400, 400)
        self.setFixedSize(400, 400)
        centralWidget=QtGui.QWidget(self)
        centralWidget.show()
        self.setCentralWidget(centralWidget)
        self.show()

        self.versionpb= QtGui.QLabel(centralWidget)
        self.versionpb.setGeometry(QtCore.QRect(130,80, 200, 200))
        self.versionpb.setText("Welcome to www.versionpb.com !")
        self.versionpb.show()

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    ui=SimpleWindow()
    sys.exit(app.exec_())




Save this code in a file as MyWindow.py .

If you try executing it in your python environment as python MyWindow you will see Small window as per screenshot below :

Simple Wndow developed in python

Simple Window developed in python

 

Step2Download and install py2exe in your machine and create a .exe generated code from it

Download py2exe via http://www.py2exe.org/ and create a setup.py file as per below code

from distutils.core import setup
import py2exe

setup(
windows=[{
'script':'MyWindow.py',
}])
excludes =  [ "mswsock.dll", "powrprof.dll" ]

where MyWindow.py is your script name . Once this is done open command prompt and execute below command

python setup.py py2exe

Once this is done successfully you will see 2 directories created in the same folder named dist and build. Inside dist directory you will see following files .

bz2.pyd            
MyWindow.exe     
library.zip        
pbcabtdll          
pkldll             
PyQt4.QtCore.pyd   
PyQt4.QtGui.pyd    
python27.dll       
pywintypes27.dll   
QtCore4.dll        
QtGui4.dll         
select.pyd         
sip.pyd            
unicodedata.pyd    
win32clipboard.pyd 
_hashlib.pyd       
_socket.pyd        
_ssl.pyd           

Now if you click on MyWindow.exe you will see your same python app will open by this executable file

Step3Create a single .exe installer from the .exe and other files created in step 2

Now if you want to distribute this application you need to distribute all of these files i.e. the .exe file depends on all the files for the app to function normally . Now in this step we will explain how to create a installer which will run a window extractor using NSIS . To do this download NSIS from this link

Now we need to create .nsis file to create this extract . One such basic sample nsis file is as below :

;NSIS Modern User Interface
;--------------------------------
;Include Modern UI
!include "MUI2.nsh"
;--------------------------------
;General

;defile
!define APPNAME "MyWindow"
!define COMPANYNAME "VersionPB"
!define DESCRIPTION "Sample NSIS Installer"
# These three must be integers
!define VERSIONMAJOR 2
!define VERSIONMINOR 2
!define VERSIONBUILD 2.0.9.0
# These will be displayed by the "Click here for support information" link in "Add/Remove Programs"
# It is possible to use "mailto:" links in here to open the email client
!define HELPURL "http://versionpb.com" # "Support Information" link
!define UPDATEURL "http://versionpb.com" # "Product Updates" link
!define ABOUTURL "http://versionpb.com" # "Publisher" link
# This is the size (in kB) of all the files copied into "Program Files"
!define INSTALLSIZE 24978
!define IMAGEDIR "../images"
!define PROGDIR "../MyWindow"
!define OUTDIR "../GeneratedEXE"

;Request application privileges for Windows Vista
RequestExecutionLevel admin

;Default installation folder
InstallDir "$PROGRAMFILES\${COMPANYNAME}\${APPNAME}"

;Name and file
Name "${COMPANYNAME} - ${APPNAME}"
OutFile "${OUTDIR}\MyWindow.exe"


;--------------------------------
;Interface Configuration
!define MUI_HEADERIMAGE
!define MUI_ABORTWARNING

;--------------------------------
;Pages

!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_COMPONENTS
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH

!insertmacro MUI_UNPAGE_WELCOME
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_UNPAGE_FINISH

;--------------------------------
;Languages

!insertmacro MUI_LANGUAGE "English"

;--------------------------------
;Installer Sections

Section "MyWindow" FilesADD

# Files for the install directory - to build the installer, these should be in the same directory as the install script (this file)
setOutPath $INSTDIR
# Files added here should be removed by the uninstaller (see section "uninstall")

file "${PROGDIR}\_hashlib.pyd"
file "${PROGDIR}\_socket.pyd"
file "${PROGDIR}\_ssl.pyd"
file "${PROGDIR}\bz2.pyd"
file "${PROGDIR}\MyWindow.exe"
file "${PROGDIR}\library.zip"
file "${PROGDIR}\PyQt4.QtCore.pyd"
file "${PROGDIR}\PyQt4.QtGui.pyd"
file "${PROGDIR}\python27.dll"
file "${PROGDIR}\pywintypes27.dll"
file "${PROGDIR}\QtCore4.dll"
file "${PROGDIR}\QtGui4.dll"
file "${PROGDIR}\select.pyd"
file "${PROGDIR}\sip.pyd"
file "${PROGDIR}\unicodedata.pyd"
file "${PROGDIR}\win32clipboard.pyd"

createDirectory "$SMPROGRAMS\${COMPANYNAME}"

# Registry information for add/remove programs
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "DisplayName" "${COMPANYNAME} - ${APPNAME} - ${DESCRIPTION}"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "QuietUninstallString" "$\"$INSTDIR\uninstall.exe$\" /S"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "InstallLocation" "$\"$INSTDIR$\""
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "DisplayIcon" "$\"$INSTDIR\Calculator.ico$\""
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "Publisher" "$\"${COMPANYNAME}$\""
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "HelpLink" "$\"${HELPURL}$\""
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "URLUpdateInfo" "$\"${UPDATEURL}$\""
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "URLInfoAbout" "$\"${ABOUTURL}$\""
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "DisplayVersion" "$\"${VERSIONMAJOR}.${VERSIONMINOR}.${VERSIONBUILD}$\""
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "VersionMajor" ${VERSIONMAJOR}
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "VersionMinor" ${VERSIONMINOR}
# There is no option for modifying or repairing the install
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "NoModify" 1
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "NoRepair" 1
# Set the INSTALLSIZE constant (!defined at the top of this script) so Add/Remove Programs can accurately report the size
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${COMPANYNAME} ${APPNAME}" "EstimatedSize" ${INSTALLSIZE}

# Uninstaller - See function un.onInit and section "uninstall" for configuration
writeUninstaller "$INSTDIR\uninstall.exe"

SectionEnd

Section "Desktop Shortcut" DesktopShort
# Start Menu

CreateShortCut "$DESKTOP\${APPNAME}.lnk" "$INSTDIR\Calculator.exe" "" "$INSTDIR\Calculator.ico"
SectionEnd

Section "Start Menu Shortcut" StartMenuShort
# Start Menu

createShortCut "$SMPROGRAMS\${COMPANYNAME}\${APPNAME}.lnk" "$INSTDIR\Calculator.exe" "" "$INSTDIR\Calculator.ico"

SectionEnd

To create more advanced NSIS scripts kindly refer these examples

Comments are closed