Python argparse and bash completion

I would like to get autocomplete in my python scripts as well in the arguments.

I never understood how bash_completion works (for arguments), but after digging out, I realized that:

  • it uses "complete" to bind the completion function to the command
  • each trailing function is basically a copy of the argument parser

The second point, in particular, is small, because I would like it to be automatically generated.

It would be best if the shell would ask my program in each TAB what to do, but I get the impression that this really does not work, is it right?

The second option, probably, is to simply write a converter from the argparse parser into the correct shell.

+48
python argparse bash-completion
Dec 05 '11 at 15:48
source share
2 answers

Shameless self-promotion: https://github.com/kislyuk/argcomplete

argcomplete provides bash completion for argparse.

+56
Nov 25 '12 at 19:50
source share

Bash "completion" is really great. And easy for programs written in Python ....

I think this is exactly what you want: optcomplete: Self-Generator shell for Python . It is available, for example, as the "python-optcomplete" package in Ubuntu.

You insert a few lines into your python program, and the user (once) runs bash a "full" program to tell bash how to execute the arguments:

complete -F _optcomplete <program> 

and now the user has finished work! By default, this gives a simple termination of software options. See an example on how to configure how completion works for a specific option. It is beautifully written and easily extensible for processing subcommands, alternative completion options, etc.!

Update:

To complete in zsh (for optparse and argparse) see genzshcomp 0.3.1: Python Package Index

As @englebip noted, we still need something similar for the new argparse module introduced in Python 2.7 and 3.2, since optparse now deprecated.

Here is a discussion of movement in this direction:

See also this background on how this is done: How do argpse (and legacy optparse) react to pressing the tab key after the python program name in bash? - stack overflow

+13
Feb 23 '12 at 18:32
source share



All Articles