Python Command Line Interfaces¶
Command line interfaces in Python may be implemented using the argparse
module or using Click.
Command Line Interfaces using Click¶
Click is a Python package for creating command line interfaces in a composable way. It supports:
- arbitrary nesting of commands
- automatic help page generation
- lazy loading of subcommands at runtime
Click has good documentation including a quickstart guide.
Callable CLI Command¶
To create a callable command e.g. $ butler ...
, at the top level of your package create a folder
called bin.src
, it should contain two files:
SConscript
with contents:
# -*- python -*-
from lsst.sconsUtils import scripts
scripts.BasicSConscript.shebang()
- A file that has the name of the CLI command the user will call. This file should contain as little implementation as possible, it should import an implementation file and call a function in it. For example:
import sys
from lsst.daf.butler.cli.butler import main
if __name__ == '__main__':
sys.exit(main())
All implementation should be placed in a folder called cli
(“command line interface”) under
<package name>/python/lsst/package/name/cli
, and the implementation of the command should go in a file
in cli
, e.g. cli/butler.py
.
- CLI utilities should go a in a file
cli/utils.py
.
Click Command¶
Commands are like the subcommand pull
in git pull
. They are implemented as functions, and declared
by decorating the function with @click.command
@click.command
def pull():
...
Commands that can be executed by the top-level script should go in a cmd
folder inside cli
, e.g.
python/lsst/package/name/cli/cmd/my_command.py
.
Click Options¶
Options are like the -a
and the -m <msg>
in git commit -a -m <msg>
. They are declared by adding
decorators to Command functions.
@click.command
@click.option(-a, --all, is_flag=True)
@click.option(-m, --message)
def commit(all, message):
...
Click Arguments¶
Arguments are unnamed parameters like my_branch
in git checkout my_branch
.
Naming¶
Use hypens for the cli invocation. Use underscores for the implementation. TODO flesh out.
## Section for Butler scripts ##
Commands are imported by the top-level butler script.
daf_butler
has a top-level script that imports commands. TODO explain DAF_BUTLER_PLUGINS
and to put the path
to the cmd
folder, and to make those commands available by the __init__.__all__
in that folder.
## WTD for non-Click scripts? ## (b/c I don’t know anything about them)