GitHunt
DB

dbarnett/python-selfcompletion

Automatically-generated command completion built on argparse

selfcompletion

selfcompletion is a layer on top of argparse to take the fine-grained model
argparse builds of the arguments your program accepts and automatically
generate an extra '--_completion' argument that generates all possible
completions given a partial command line as a string.

The '--_completion' argument in turn is used by a generic bash programmable
completion script that tries '--_completion' on any program that doesn't have
its own completion already available, renders the output of the program's
built-in completion if available, and otherwise silently falls back to the
shell default.

About

How to Use

prog.py:
#!/usr/bin/env python
try:
from selfcompletion import SelfCompletingArgumentParser as ArgumentParser
except ImportError, e:
from argparse import ArgumentParser

parser = ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

$ chmod +x prog.py
$ ./prog.py
0 4 8 --help
1 5 9 --sum
2 6 --_completion
3 7 -h
$ ./prog.py -
--_completion -h --help --sum
$ ./prog.py 1
0 1 2 3 4 5 6 7 8 9

Why?

Command-line completion is very, very cool, and along with good built-in help,
can make even the most complex program usable. Unfortunately, it's a pain to
implement. It requires an entirely separate shell script per shell syntax
to support (e.g., bash, zsh, fish), it's a challenge for maintainers to
distribute, and it must be kept in sync with changes in the program itself or
else it becomes less useful or even gets in the way.

selfcompletion is an attempt to create a standard, and reduce a matrix of
supported shell/application combinations to a list of supported shells and a
list of compliant programs. Now all python software using argparse can add
fine-grained command-line completion essentially for free!

Installing

selfcompletion uses distutils2. To install, run
pysetup install
or
python -m distutils2.run install

Languages

Python100.0%

Contributors

Created October 17, 2011
Updated July 18, 2024