14

Say I have a program hello.py and one possible valid argument to it is:

./hello.py autoawesomesauce

Is is possible to type in:

./hello.py auto[tab]

at which point the partially completed argument is sent to hello, which recognizes it as such and then completes it on the shell to:

./hello.py autoawesomesauce

I know git does something like this, but can it be done for a Python script + Bash?

migrated from stackoverflow.com Apr 22 '11 at 15:02

This question came from our site for professional and enthusiast programmers.

  • 4
    The Python script can't. bash must. – Ignacio Vazquez-Abrams Apr 22 '11 at 14:57
  • upvote for what exactly? – RestRisiko Apr 22 '11 at 14:58
7

On Linux systems, you can generally find a large number of example scripts under: /etc/bash_completion.d. If you source these scripts, then you will get the autocomplete behavior.

I've included an example from that directory. This is the completion script for unrar.

_unrar()
{
    local cur

    COMPREPLY=()
    _get_comp_words_by_ref cur

    if [[ "$cur" == -* ]] ; then
        COMPREPLY=( $( compgen -W '-ad -ap -av- -c- -cfg- -cl -cu \
            -dh -ep -f -idp -ierr -inul -kb -o+ -o- -ow -p -p- -r -ta \
            -tb -tn -to -u -v -ver -vp -x -x@ -y' -- "$cur" ) )
    else
        if [ $COMP_CWORD -eq 1 ]; then
            COMPREPLY=( $( compgen -W 'e l lb lt p t v vb vt x' -- "$cur" ) )
        else
            _filedir '@(rar|RAR)'
        fi
    fi

} &&
complete -F _unrar -o filenames unrar
  • What is _get_comp_words_by_ref? – e-info128 May 18 '18 at 8:56
4

This functionality has zero to do with Python. This is a pure functionality of the underlaying shell. So read up the bash docs on auto-completion.

Google for "bash auto-completion" and you will find at least 5 reasonable docs under the first 10 hits.

  • Which means it may be a good idea to wrap your Python script in a Bash script, letting the Bash script do as much argument handling/parsing as possible. – Kazark Sep 11 '12 at 18:31
0

See this related StackOverflow post.

complete 'your_command' 'p/*/`echo list_of_your_options`/'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy