Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to create exe and MSI files using cx_freez?

Exe and MSI Using Cx_freeze

In this article, you will learn how to create exe and MSI using cx_freez. So lets Start, It is a Python library that is used to freeze python scripts, the whole project either GUI or console-based same as the other libraries do like py2exe, py2app, and pyinstaller. It provides support on almost every platform. The current version of cx_freeze supports python 3.5 and above.

In this blog, you will learn how to create an exe and MSI file of python code with the pyqt5 GUI app. For doing this you must have.

  • Python 3.5+
  • PyQt5
  • Cx_freeze

Create a sample python project

I am using pycharm as a development IDE for this. You can use any other development tool.

Steps to create a python exe file

First, I created a python project titled python_exe. Click on File -> new project. Set project location and name and select a new environment and select the right interpreter, in my case it is python 3.7.

  • As I have a GUI file so I need pyqt5 for GUI and cx_freeze for exe file creation. Before doing anything first install these two modules using the following commands.

pip install cx_freeze

pip install pyqt5

  • After project creation, copy your project files here with the main file. If your project has distributed in different directories, make sure you must have an empty __init__.py file in each directory to avoid the module not found an error. In my case, I have the following files.
  • I have a signup GUI created and called here in the main.py file
import sys
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import QGraphicsDropShadowEffect
from signup_controller import Ui_SignUpController

def run():
    stylesheet = """
    QLabel{
    font-family:TitilliumWeb-Regular;
    }
    QCheckBox{
    font-family:TitilliumWeb-Regular;
    }
    QLineEdit{
    font-family:TitilliumWeb-Regular;
    }
    QTextEdit{
    font-family:TitilliumWeb-Regular;
    }
    QPushButton{
    font-family:TitilliumWeb-Regular;
    }
     QWidget#widget_main {
    border-image: url("app-icon/website-login-background.jpg");
    background-repeat: no-repeat;
    background-position: center;
    }
    """
   
app = QtWidgets.QApplication(sys.argv)
    app.setStyleSheet(stylesheet)
    frame = Ui_SignUpController()
    shadowEffect = QGraphicsDropShadowEffect()
    shadowEffect.setBlurRadius(30)
    shadowEffect.setOffset(0)
    shadowEffect.setColor(QtCore.Qt.white)
    frame.frame_main.setGraphicsEffect(shadowEffect)
    frame.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    run()
  • When I run this main.py file my gui look like.
  • Now, right-click on the project and add a new python filename as setup.py and copy the following code.

import sys
from cx_Freeze import setup, Executable

application_title = “OpenCvAPI Client”

main_python_file = “main.py”


includes = [“atexit”,“re”]
packages = [“cx_freeze”]
excludes = []
files =  [‘app-icon/’]


build_exe_options = {
    ‘includes’: includes,
    ‘excludes’: excludes,
    “packages”:packages,
    ‘include_files’: files
    }
base = None
if
sys.platform == “win32”:
    base = “Win32GUI”

setup(
    name = application_title,
    version = “0.1”,
    description = “Opencv api client gui program”,
   
options = {“build_exe”: build_exe_options},
    executables = [
        Executable(
            main_python_file,
            base = base,
        )
    ]
)

Main Parameters:

application_title = “Title for your application”

main_python_file = “set here your main entry python file”

include = includes all the libraries and modules you want to be build

exclude = define libraries that you don’t want to include

files = define files that you want to be in the exe or MSI installation files.

  • Now, open a terminal in the project ma directory and execute the following command

python setup.py build

  • Now, check your main project directory there should be a build directory inside there should be the main.exe file.

How to create an MSI installation file:

To create one complete installation file using cx_freeze, you need to set some parameters in the setup.py file.

Put this in the setup.py file and add this variable to the setup()

shortcut_table = [
    (
        "DesktopShortcut",        # Shortcut
       
"DesktopFolder",          # Directory_
       
"OpencvAPI",              # Name
       
"TARGETDIR",              # Component_
       
"[TARGETDIR]OpenCvAPI.exe",# Target
        
None,                     # Arguments
        
None,                     # Description
        
None,                     # Hotkey
        
None,                     # Icon
        
None,                     # IconIndex
        
None,                     # ShowCmd
       
'TARGETDIR'               # WkDir
    
)
    ]
# Now create the table dictionary
msi_data = {"Shortcut": shortcut_table}
bdist_msi_options = {
    'data': msi_data,
    'add_to_path': False,
    'initial_target_dir': r'[ProgramFilesFolder]\%s' % (application_title),
    "upgrade_code": "{96a85bac-52af-4019-9e94-3afcc9e1ad0c}"
}
setup(
    name = application_title,
    version = "0.1",
    description = "Opencv api client gui program",
    options = {"bdist_msi" : bdist_msi_options,'build_exe': build_exe_options},
    executables = [
        Executable(
            main_python_file,
            base = base,
            targetName="OpenCvAPI.exe",
        )
    ]
 
 

Now open the command terminal and run the following code to create the msi file

                python setup.py bdist_msi

After you run the above command you will see a new Directory with the name of dist. This directory contains your OpenCvAPI.msi file.

In the above code, you see some extra parameters.

Parameters:

shortcut_table = if you want to create a shortcut after installation then add this variable with the specified parameters and values

add_to_path = if you want to add the application path to the system variable set to True

Initial_target = this option is used when installation MSI file it will set the specified directory path

upgrade_code = set an upgrade code (when you want to change the application and the user install it will show you the modify option and will automatically modify itself)

description = description text that will be shown in the installation of application

version = set version number for your application

options  = set the build option for exe and MSI

targetName = if you want to change the generated exe filename

icon = API.icoset icon for your application exe

How to start your installed application to run at window start

When you logged in to a window there are a lot of applications start executing. There are two option you can get and achieve

  1. To create a service and installed it on your system
  2. To create a bat script and add to the start directory

I cover the second option to do so you will need to add some code that will create a .bat file and add to the start directory. When you next time logged in this script will be run automatically.

Step to add the exe file to run after window logged in

  1. Create a python file name as add_to_registery.py in the current project root directory and add the following code
# !/usr/bin/python3
import sys, os
import getpass


def AddToRegistry(file_path=""):

    # determine if application is a script file or frozen exe
   
if getattr(sys, 'frozen', False):
        file_path = os.path.dirname(sys.executable)
    elif __file__:
        file_path = os.path.dirname(__file__)

    file_path = os.path.join(file_path, 'OpenCvAPI.exe')
    USER_NAME = getpass.getuser()
    if file_path == "":
        file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'OpenCvAPI.exe')
    bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME
    with open(bat_path + '\\' + "opencv_api.bat", "w+") as bat_file:
        bat_file.write(r'start "" %s' % ("\""+file_path+"\""))

Everything is fine you need to just replace the your exe file name (OpenCvAPI.exe)

  • Now open signup_controller and call the add_to_registry function.

def get_started(self):
    username=self.lineEdit_username.text().lower()
    password=self.lineEdit_password.text()
    confirm_password=self.lineEdit_confirmPassword.text()
    if username=="" or password=="" or confirm_password=="":
        show_message_box(QMessageBox.Critical, "Error","Please fill out all the fields!")
        AddToRegistry()

Now run the MSI file and install it.


After executing the OpenCvAPI.exe file and clicking on the Get Started button. Open RUN by pressing start+r and type shell: startup

Yeah, our file is created successfully.

Summary!

In this tutorial, you learn. How to create an exe file How to create an MSI file Different parameters of the exe file are described How to execute your exe file after window log in.

 

The post How to create exe and MSI files using cx_freez? appeared first on Fukatsoft Blog.



This post first appeared on How Cancer Begins, please read the originial post: here

Share the post

How to create exe and MSI files using cx_freez?

×

Subscribe to How Cancer Begins

Get updates delivered right to your inbox!

Thank you for your subscription

×