DEV Community

Cover image for How to convert .py to .exe? Step by step guide.
Eshleron
Eshleron

Posted on • Updated on

Python to .exe How to convert .py to .exe? Step by step guide.

Auto PY to EXE

The only tool that we are gonna be using is Auto PY to EXE!

Auto PY to EXE is an amazing application for making .exe file out of your project whether it is one .py file or any number of them.
The application has a nice gui and looks like this:

alt text

How to start

Step 1. Installation

Installing using PyPI:

To install the application run this line in cmd:

pip install auto-py-to-exe

To open the application run this line in cmd:

auto-py-to-exe

Note: if you have any problems installing this way or you want to install it from GitHub go to the main page or watch this instructional video by the developer of "Auto PY to EXE" himself.

For more additional information use this

"Issues When Using auto-py-to-exe"

Step 2. Converting

There are few main options you need to choose:

  1. Pick your .py file
  2. Pick "One Directory" or "One File" option
  3. Pick additional files

1. Pick your .py file

If you have multiple files choose one that starts the program.

2.1. "One Directory" option

alt text

Pretty simple. When choosing "One Directory" option "Auto PY to EXE" will put all dependencies in one folder. You can choose Output directory in "Advanced" menu. If you have media files like icons and backgrounds you shouldn't have any problems using them inside your .exe if you place media files/folders in the Output directory.
Something like this:

alt text

2.2. "One File" option

alt text

When choosing "One File" option "Auto PY to EXE" will create one .exe file containing all dependencies but NOT MEDIA FILES. If your program has only default Windows gui with no icons, backgrounds, media files or you are OK with placing media folder near .exe file feel free to skip the following explanation. For those who want to pack media files into .exe file itself read paragraph 3.

3. Pick additional files

There is a menu in "Auto PY to EXE" called "Additional Files" that lets you add files of your choice. There is a catch though. "Auto PY to EXE" uses pyinstaller which unpacks the data into a temporary folder and stores this directory path in the _MEIPASS environment variable. Your project won't find necessary files because the path changed and it won't see the new path either. In other words, if option "One File" is chosen picked files in the "Additional Files" menu will not be added to .exe file. To work around this you should use this code provided by developer of Auto PY to EXE here

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
try:
    # PyInstaller creates a temp folder and stores path in _MEIPASS
    base_path = sys._MEIPASS
except Exception:
    base_path = os.path.abspath(".")

return os.path.join(base_path, relative_path)
Enter fullscreen mode Exit fullscreen mode

To use this code in your project replace the link to the media file you have now
For example:

setWindowIcon(QIcon('media\icons\logo.png'))
Enter fullscreen mode Exit fullscreen mode

with

setWindowIcon(QIcon(resource_path('logo.png'))
Enter fullscreen mode Exit fullscreen mode

Now the link will be referenced correctly and chosen files successfully packed into .exe file.

For comparison:
Possible link before

"C:\Users\User\PycharmProjects\media\icons\logo.png"
Enter fullscreen mode Exit fullscreen mode

Possible link after

"C:\Users\User\AppData\Local\Temp\\_MEI34121\logo.png"
Enter fullscreen mode Exit fullscreen mode

Press CONVERT .PY TO .EXE

alt text

Wait

alt text

Step 3. Run your program!

Now everything is done!

Run it. Test it. See what`s up.

Make sure everything works well.

You made One Directory

Every file you need should be in the single directory.

You made One File

This way you should have single .exe file. If you had a need and if done correctly your .exe file will be packed with all media inside it. You will not need any media files/folders present with .exe file for it to display them properly.


P.S.

If you have any feedback or suggestions on what important information should be added feel free to let me know!
This guide is not a description of every possible option done every possible way.
I hope you found that information useful!
Good luck with your projects!

Oldest comments (104)

Collapse
 
joehobot profile image
Joe Hobot


mv somefile.py somefile.exe

😛

Collapse
 
eshleron profile image
Eshleron

😛

Collapse
 
bauripalash profile image
Palash Bauri 👻

GUI Wrapper for PyInstaller! Gonna try

Collapse
 
lyfolos profile image
Muhammed H. Alkan

It's not good to do this. The performance will stay same (even decreased) and it will lose the cross-platform ability.

Collapse
 
vguarnaccia profile image
Vincent Guarnaccia

I think a common use case is sharing a Python program with someone who might not have the interpreter installed.

Collapse
 
fjo_costa profile image
Fernando Costa

Nice!! How does this handle zipfile?

Collapse
 
eshleron profile image
Eshleron • Edited

If I understood your quiestion correctly then that's what I found pythonhosted.org/PyInstaller/advan...

Collapse
 
calebwin profile image
Caleb Winston

This looks great! I do want to give a quick shout-out to Nim

If you're looking to build performant executables and Python is what you're really comfortable, I think you'll find Nim's syntax pleasingly similar; and the performance improvements are real 😀

Collapse
 
celiasty profile image
Celiasty

I can't install it :
Command ""c:\program files (x86)\python37-32\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\NATHAN~1\AppData\Local\Temp\pip-install-d_n5yima\future\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\NATHAN~1\AppData\Local\Temp\pip-record-oaye_ir1\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\NATHAN~1\AppData\Local\Temp\pip-install-d_n5yima\future\
You are using pip version 18.1, however version 19.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

I've try to upgrade pip but i can't uninstall my last version

Collapse
 
eshleron profile image
Eshleron • Edited

It's not pip version problem I think. I would reinstall pip or python(if nothing helps) if googling doesn't help. Couple months passed since you asked, probably you already have a solution.

Collapse
 
biswarup1290dass profile image
biswarup1290dass

I am facing the below issue while converting py to exe. It if failing at Analysis due to log formatting syntax.

Collapse
 
biswarup1290dass profile image
biswarup1290dass

I am facing the below issue while converting py to exe. It if failing at Analysis due to log formatting syntax.

[thepracticaldev.s3.amazonaws.com/i...]

Collapse
 
eshleron profile image
Eshleron

Hi!
1.If you still have the problem I would look and the string itself with
log.error(f""). Dont think that you can do what I think you are trying to do.

2.If second error is present after you delt with the first one, then simple recomendation is to reinstall pyinstaller. I had multiple problems with converting and they mostly got solved by restarting converting process.

Collapse
 
elputojay profile image
𝕛𝕒𝕪 🇪🇸

Hey buddy, thanks for creating this. I have a problem though: in my python script I call several files that are in the current working directory, based on relative paths to simplify it. Once it's compiled to the exe, it seems that the program goes to the root folder of the computer as an absolute route. This kind of defeats the object since my program has to run in a folder with other files being added and removed.

What can I do to force the .exe to work on relative paths exactly the same way I have my script?

thanks

Collapse
 
eshleron profile image
Eshleron • Edited

Hi!
1.What I usually do is get an absolute path so the script\scripts always know where they are

import os
dir = os.path.dirname(__file__)
abs_path = os.path.join(dir, DB_DOCS_NAME)
variable = open(abs_path)
Enter fullscreen mode Exit fullscreen mode

2.If the main script is looking in the wrong place for other scripts then probably your imports are not correct.
Try to use this resource
realpython.com/absolute-vs-relativ...

Hope that I helped in some way

Collapse
 
leandadearaujo profile image
leandadearaujo • Edited

hey when I add the dll files using add files drop down and create the exe , when i try to open the exe it says "failed to compile the exe file_name" , can you please help out with this it urgent as well Thank you so much in advance

Collapse
 
eshleron profile image
Eshleron • Edited

Hi! Can you please send some screenshots?

Collapse
 
tejasmandre profile image
Tejas Mandre

Does this pack all the libraries that need to be imported in my python code in my .exe file ?

Collapse
 
eshleron profile image
Eshleron

Yes, it does.

Collapse
 
fatmaelsherif profile image
Fatma-Elsherif

SystemExit: Unable to find "C:\Users\medo2\nltk_data" when adding binary and data files.

Project output will not be moved to output folder
Complete.

Collapse
 
jromano1 profile image
JPR

I'm a VERY inexperienced python user, but have built a couple of very basic scripts with an small interactive UI (using Tkinter/pyodbc).

My question is - once the script is converted to .exe and distributed to the users (who will save and launch from the desktops), do they need to have anything else installed, or is the .exe truly fully self contained?

My goal is to be able to write a script, convert to an executable, send to my users, and have them use that for some basic daily work.

Thanks!

Collapse
 
eshleron profile image
Eshleron • Edited

Hi! To use .exe an end user doesn't need anything. Once it's .exe and not .py format your script should be usable without any additional software. Check for correct paths if you're opening smt inside your program.

But make sure (if you work with SQL DB) that it's packed with evething it needs. I haven't tried to work with DB and PyInstaller so I dont know how it will be able to pack it. I guess to PyInstaller it's just the same library as any other.

Collapse
 
jromano1 profile image
JPR

Thank you for the reply!

It seems that that's not always the case, and the converted .exe doesn't always contain the same stuff.

For example, and I apologize for not having the code and error messages anymore... I had a script (in PyCharm) that pulled a 2 values from a SQL table, then just subtracted them and printed out the difference (up to the thenth position). It worked fine, but once I converted it, I received an error that the "Decimal" module/library could not be found. I never called "Decimal", but one of my colleagues said it was part of the standard python installation. So we assumed the issue, then, was that the "Decimal" library/module/package was excluded from the final build.

I've since been unable to resolve this problem and built the app using something else, but I'd love to try again sometime.

Collapse
 
claudiaacerra profile image
claudia acerra

Wow did not know this app was out there. Thank you for your hard work. I have been trying to use pyinstaller to distrinute my tkinter app with SQLite DB... The error I get using pyinstaller is the same one I get using your tool. And that is when I try and use data from the DB or try to update the DB I get the following error:

sqlite3.OperationalError: no such table: track2

Any ideas?
Again thank you!

Collapse
 
eshleron profile image
Eshleron • Edited

Hi!
Try this solution on stackoverflow

Check out this method to making sure that you are working in the right directory.
one way to do it

Let me know if that helps or not!

Collapse
 
prohashim profile image
ProHashim • Edited

Hi there! Thanks a lot for this beautiful article.
But when I try to run auto-py-to-exe I am getting this error:

Traceback (most recent call last):
File "C:\Users\Muhammad Hashim\AppData\Local\Programs\Python\Python38\Scripts\auto-py-to-exe-script.py", line 6, in
from pkg_resources import load_entry_point
File "C:\Users\Muhammad Hashim\AppData\Local\Programs\Python\Python38\lib\site-packages\pkg_resources_init.py", line 3251, in
def _initialize_master_working_set():
File "C:\Users\Muhammad Hashim\AppData\Local\Programs\Python\Python38\lib\site-packages\pkg_resources__init
.py", line 3234, in _call_aside
f(*args, **kwargs)
File "C:\Users\Muhammad Hashim\AppData\Local\Programs\Python\Python38\lib\site-packages\pkg_resources__init
.py", line 3263, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File "C:\Users\Muhammad Hashim\AppData\Local\Programs\Python\Python38\lib\site-packages\pkg_resources__init
.py", line 583, in _build_master
ws.require(
requires)
File "C:\Users\Muhammad Hashim\AppData\Local\Programs\Python\Python38\lib\site-packages\pkg_resources__init
.py", line 900, in require
needed = self.resolve(parse_requirements(requirements))
File "C:\Users\Muhammad Hashim\AppData\Local\Programs\Python\Python38\lib\site-packages\pkg_resources__init
_.py", line 786, in resolve
raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'Eel==0.11.0' distribution was not found and is required by auto-py-to-exe

Collapse
 
eshleron profile image
Eshleron • Edited

Hi!
It says you need Eel 0.11.0. Try to install/reinstall Eel and launch auto-py-to-exe again.

Collapse
 
prohashim profile image
ProHashim

Thanks a lot !!!

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more