Sunday 20 July 2014

A small sidenote on cx_Freeze, converting (GUI) scripts into exe and the annoying dos window

Hi everyone!

As you know, Python scripts need to be interpreted in order to run on your computer. Let's say that you want to give your brand new program to your friend who, for some reason, is reluctant to install Python and does not like using the command line or related things. Well then building a simple GUI (Graphical User Interface), with Tkinter for instance, is the right choice. However, we have not solved the user friendliness issue since even with a GUI, our script needs to be run with Python. The solution then, is using the module cx_Freeze to "convert" our script into an executable file (.exe) which can be run on windows.
I have been using cx_Freeze for just 3 months I guess, and I find it practical and useful. There are other modules which serve the same purpose, however some of them (py2exe for instance) are still not available for Python 3. More information on http://cx-freeze.sourceforge.net/

Here are the main steps to convert your .py program into an .exe:
1.Check that your script works fine
2.Create a setup.py file as below
3.Put setup.py and your script in the folder pythonxx (python33 if you have python 3.3)
4.Open the command line (cmd) and go to the pythonxx folder
5.Type in: python33\python.exe setup.py build
6.Press enter. Python will build your exe and put a "Build" folder in your python33 folder.
7.Check out the Build folder in python33 where the executable lies. There you go!


The setup file should contain this (sqrt.py is the script to converted):
from cx_Freeze import setup, Executable

setup(
    name = "sqrt",
    version = "0.1",
    description = "test",  #you can put here whatever you want
    executables = [Executable("sqrt.py")],
    )


Once you have had fun with your new executable script, if your script had a GUI interface, such as Tkinter, you will find an annoying thing: the dos window!!! It will not go away no matter what you do. It just comes up every time you run the .exe. The solution to this problem: you need to edit the setup.py file and reconvert the script. Here is the setup.py if your script has a GUI such as Tkinter:

import sys
from cx_Freeze import setup, Executable

base = None
if (sys.platform == "win32"):
    base = "Win32GUI"


setup(
    name = "sqrt",
    version = "0.1",
    description = "test",
    executables = [Executable("sqrt.py",base=base)],
    )

And your dos window will not appear every time you run the .exe. I had a hard time finding this and I hope it will be useful to someone.
Enjoy!

2 comments: