Convert Python code to EXE file - Here's how
Python programs can usually only be run on a computer on which Python is already installed. In this practical tip, however, we explain how you can create an EXE file based on a Python program.
Convert Python code to EXE file - Here's how
However, before you convert the Python code into an EXE file, you should first change the environment variables (under Windows).
- Then open the command prompt and enter "pip install cx_freeze".
- First you have to create a new file called "setup.py", in which you insert the commands "import sys" and "from cx_Freeze import setup, Executable" at the beginning.
- With the command »build_exe_options = {" packages ": [" os "], " excludes ": [" tkinter "]}« you can then set various properties for the EXE file.
- Then you have to add the commands »base = None« and »if sys.platform ==" win32 ":«. Below this, insert the command »base =" Win32GUI "« (shifted to the right with the tab key).
- Now you have to define the setup function in which you set various properties. You can specify the name with the command »setup (name =" Program ", ". Below this you can insert the command "version =" 0.1 ", " (which is positioned to the right with the tab key), which stands for your version number. Then place A description for the EXE file with the command »description =" My first program! ", « In the next step you can import the already defined options with the command »options = {" build_exe ": build_exe_options}, «. Finally, you have to use the command »executables = [Executable (" programm.py ", base = base)])« to select the Python file to be converted into an EXE file.
- To create your EXE file, you first need to make sure that the setup file and your actual Python file are in the same folder. Then open CMD at this point and execute the command "python setup.py build", which you can use to create the EXE file. If this command does not work for you, test the command "py setup.py build". With the command »python setup.py bdist_msi« (or »py setup.py bdist_msi«) you can also create an MSI file (Windows Installer).
- However, note that the instructions only work for programs without a GUI. If you have programmed a GUI, you need a different setup file.
More tips about Python in the CHIP guides
Tip: You can find further programming tutorials on our Python programming language topic page. There we will show you, for example, how you can program loops in Python.