понеделник, 24 февруари 2020 г.

How to convert .py to .exe

    Have you ever wondered how to convert your .py file with code into independent program that can run when Python isn't installed on the PC/laptop? Well, there are a couple of ways to do that and my modest advise is to try all of them and decide which one fits your way of work best. Right now I will share the way I transform .py into .exe.

    I am using pyinstaller and you have to install it like any other Python module in order to to use it. I am working on Windows and in this case we need the command line:

  • Type cmd in the search field of your Start menu and when "Command prompt" appears just click on it.  
  • Type "cd" /it stands for "change directory"/ followed by interval and paste the path to where Python is installed on your computer, then hit enter. The command looks like below in my case: 
cd C:\Users\Kostadin\AppData\Local\Programs\Python\Python36\Scripts
  • Once in the "Scripts" folder of your Python installation run the following command:
pip install pyinstaller


And wait a bit, it should be installed in a minute. The first step when using pyinstaller is quite the same as the first steps when installing it:

  • Go to the same "Scripts" folder via command prompt
  • Type the command below:

pyinstaller --onefile [path\to\file-to-be-converted(.py)]

This is basically enough to produce the .exe file which can be found in Scripts\dist folder. However, this will put all libraries & modules you have installed on your Python distribution in your executable file which will make it huge. It's kind of weird to have 120MB .exe for ~50KB .py coding file, isn't it? To avoid that you can exclude libraries that are not needed for proper functioning of your executable. Just add --exclude [name-of-library] between --onefile and [path\to\...]:

pyinstaller --onefile --exclude scipy --exclude pandas --exclude pyqt5 E:\python\v3\main.py

That's all for now. I am searching for ways to further compress the executable file and will indeed share once I find such a way.

Няма коментари:

Публикуване на коментар