Python Apps the Right Way: entry points and scripts
There are multiple ways to write an app in Python. However, not all of them provide your users with the best experience.
One of the problems some people encounter is writing launch scripts. The
best way to handle this is the Entry Points mechanism of Setuptools, and a
__main__.py file. It’s quite easy to implement. If you’re interested,
read on to learn more!
Requirements and Desired Results
You will need:
a Python project
a setup.py file using setuptools
the following directory structure:
entry_points_project is also where the README and other auxiliary files
my_project contains all the Python code.)
When you’re done, you will have a project that can be executed by:
python -m my_project
Provided that you have your Python directory and its
Scripts\ subdirectory on
the %PATH%, this will also work in Windows.
Looking for a project template?
Step 1: create a
In order to implement the first desired result, you need to create a
__main__.py file in your package. This file needs to contain a
function that takes no arguments, and also a special passage to determine code
if __name__ == "__main__":idiom, as documented here, is used to check whether this is executed as the top-level file, or if it has been imported by someone else (in this case, executing the
main()function is not always intended).
main()function must not take any arguments, because that’s how
Step 2: adjust
This is the real deal: create the entry points in your
You must use setuptools, otherwise this won’t work.
The most important piece of code is the
The declaration reads
If you are developing a GUI application (in Tkinter, PyQt/PySide, wxPython, PyGTK, PyGame…), you should change the declaration to
gui_scripts. On *nix, this makes no difference, but on Windows, it means that running your script by opening the created
.exefiles does not show a console window. Note that stdout/stderr do not work in that mode under Windows, which can lead to spurious application crashes. (GUI-only processes cannot use stdout/stderr because they don’t have a console attached)
You can create multiple scripts this way. You can also have multiple
gui_scriptsin one setup file.
All code samples are freely reusable, but if you mention where you got them from, it’d be really nice.