Python scripts executable from console / command prompt

1 minute read

Each Python package’s setup.cfg can make Python scripts callable from any directory, by adding them to your system PATH via the <PythonDistroRoot>/bin directory. On a typical Anaconda Python install, the shortcuts to these scripts are installed in a directory like ~/miniconda3/bin/

Make sure your console_script entry_points are set up correctly before running pip install, or you will get the VersionConflict error

Here is a simple example addtwo.py, that we wish to run directly from console (in any directory) as

addtwo 3.5

to get result 5.5. Note that the end user doesn’t even know they’re running a Python script.

#!/usr/bin/env python
from argparse import ArgumentParser


def addtwo(x: float) -> float:
    return x + 2


def main():
    p = ArgumentParser(description='adds two to number')
    p.add_argument('x', help='number to add two to', type=float)
    P = p.parse_args()

    print(addtwo(P.x))


if __name__ == '__main__':
    main()
  1. For each function you wish to have be accessible from anywhere on the system be sure there is a function that handles console arguments as in the example above.
  2. add to setup.cfg like:
    [options.entry_points]
    console_scripts =
      addtwo = addtwo:main
      addthree = addthree:main
    

    where I assumed you also have a similar Python script addthree.py.

Notes

  • Fix pkg_resources.VersionConflict for console_scripts entry_points.
    If you execute pip install -e . before you’ve finished preparing the scripts, bad copies of the scripts are retained in the bin directory with a .py extension. Properly installed entry points do not have any file extension.

    Fix this by going into your ~/miniconda3/bin or equivalent, and remove the addtwo.py script there (where addtwo is replaced by the name of your script).

Leave a Comment