Creating executables with PyInstaller

Python provides various libraries (i.e. Pandas, Scikit-learn) for data analysis and machine learning. This makes Python one of the most widely used languages in this field. In fact, Forbes named Python one of the top 10 technical skills in terms of job demand growth.

Most of the times you are required to create an .exe file for your Python scripts. This will be a bit of challenge if your project uses too many libraries (which I will be discussing in my next article). Therefore, in this article I am focusing on creating .exe files from a simple Python scripts

Basically, there are many tools to create executable files from Python scripts. Most popular and widely used tools are py2exe and PyInstaller. However, I encountered few version incompatibility issues with py2exe, thus moved to PyInstaller.

Firstly, I will show you how to create a set up file using a simple Python script. Then I will move to a more complex scenario.

OK. Let's create our first set up file using a simple Python script, which takes command line inputs and writes to a text file.

Step 1:  Create a folder name, 'Test python set up'  (you can give any name you prefer). Create a blank Python script. Save it as test.py and place it inside the folder.

Step 2: Write the following Python code in test.py.

if __name__ == '__main__':
  user_input=input('Enter text: ')
  file = open("testfile.txt", "w")
  file.write(user_input)

  file.close()


Step 3: Install PyInstaller. You can do this in two ways. Either using command line or directly downloading PyInstaller and running the set up. 

If you' re using the command line, type: pip install pyinstaller. This will install the latest version of PyInstaller.

Otherwise you can directly download the set up from their website. Now run the PyInstaller set up and install it in your computer.

Step 4: This is the final step.  After successfully installing PyInstaller you can go to the command line and change the folder path to the  'Test python set up', and run the following command.  
pyinstaller test.py

Now go to the folder, you will see PyInstaller has created two folders, build and dist.

Now go to the dist folder, you will see test.exe file has been created successfully. Now double click on it and run it. You will be prompted to enter text. Once you typed, press enter. You can see your Python set up file has created a text file called, testfile.txt in dist folder. When you open it you will see the text you have just entered.

Congratulations!! 

You have successfully created your first Python set up using PyInstaller. In my next article I will walk you through a more complex scenario where a set of Python scripts being executed and machine learning libraries are in use.










Comments

Popular posts from this blog

Creating executables for machine learning Python scripts