Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating executable from Python script while acquiring small output size

My question might already have been answered somewhere but still, I can't find a straightforward answer to it yet. I want to create a standalone executable from python code. I've already tried a bunch of solutions like py2exe, pyinstaller, etc. But my problem is the large output file size. For example, in pyinstaller a simple hello world compile to 5MB file. After a lot of searches I've found Cython which creates a c file from python code then I tried to compile it with MSVC 2015 and generated the exe file but it depends on python3x.dll file.

So Is there any way to compile the python code to stand alone exe file with a small size?

If it is not, how to bundle the executable file with msvc?

I'm using python3.4 but is there any difference between python2 and 3 in this manner? I am using these commands to first generate c file then compile it to exe:

python -m cython test.py --embed
cl  /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python34\include -Ic:\Python34\PC /Tctest.c /link /OUT:"test.exe" /SUBSYSTEM:CONSOLE /MACHINE:X64 /LIBPATH:c:\Python34\libs /LIBPATH:c:\Python34\PCbuild
like image 423
Masoud Rahimi Avatar asked Jul 24 '17 05:07

Masoud Rahimi


People also ask

Can you turn a Python script into an executable?

If you're used to working with the terminal, then the PyInstaller library will be the best option. To install PyInstaller follow these steps. Step 3: Once you're in the right directory, write a command with the following syntax pyinstaller --onefile name_of_script.py in the terminal to make the script executable.

How can I convert a .py file to a .exe file?

In this section, we can also modify the path for where we want to export the files generated by our executable file: to do this, select the “Settings” toggle option and browse to the output directory of your choosing. The last step is to select “Convert . py to .exe” to convert our Python file.


1 Answers

As far as I know the relatively big size of the executables results in the fact, that pyinstaller links to ALL dependencies of one library. So if you use big libraries as e.g. Matplotlib you will get executables with the size of around 150MB. At least that is my point of view after working with pyinstaller for about two month. One thing I have not tried yet is to play around with the "exclude" option. I have read somewhere that it is possible to reduce the file's size if you exclude specific modules. Unfortunately I can not find the source where I read it anymore.

EDIT:

I know it's been a while but I managed to reduce the size of the executable by excluding some files. That way I was able to reduce an executable with a size of 208MB to a size of 70.3MB. I Just followed the example here

Python: Excluding Modules Pyinstaller

like image 124
Marcel S. Avatar answered Oct 21 '22 16:10

Marcel S.