2

When you install Git on your computer, it can be run from the terminal with "git". Similarly, Python can be run with just "python" or "py".

If I make a CLI with argparse and Python, is there a way to have users simply install it and use it in the terminal just by typing

$ myCLI -option

Rather than

$ python path\to\myCLI.py -option

Like all the CLI's I use/interact with do?

1 Answers1

0

Crude Solution

Your script just needs to be somewhere in the user's $PATH (and to have no extension if you don't want them to type myCLI.py). Additionally it needs to start with a magic comment #!/usr/bin/env python3 (If you are running Linux) and be executable (on linux chmod +x myCLI prior to distributing it). Alternatively you create a script in the native shell language of the desired OS (so sh for linux) which calls python3 /path/to/script or python -m module or the like.

If you you name your main script without a .py it prevents you importing it from anything else, so the usual approach is to have an 'entrypoint' script which consists of something like:

#!/usr/bin/env python3
from myApp import main
main()

(see the PyPa docs for a discussion)

Better solution

Of course, you need to deploy your entrypoint script somewhere in the end-user's $PATH. This can be more intersting, but luckily the whole thing is handled by setuptools, and you don't even need to write a script: you just need an entry point function:

Use console_script entry points to register your script interfaces. You can then let the toolchain handle the work of turning these interfaces into actual scripts

official docs

you just put in your setup.py:

setup(
    entry_points = {
        'console_scripts': [
            'PKG_NAME = package.module:func',
        ],
    }
)

and anyone who types PKG_NAME will effectively run package.module:func() (so func is your entrypoint main() function above).

See this question for a discussion of the merits of this approach over the old approach of writing separate scripts for each platform.

Note that if you're not building your app as a python package, but are using some other packaging standard (archlinux PKGBUILD or .deb or whatever) you can still take the same approach---just write the entry point script as above and have the package place it somewhere in the user's $PATH.

2e0byo
  • 5,305
  • 1
  • 6
  • 26