Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
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
add comment

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

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

3 Answers

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
share|improve this answer
add comment

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.

share|improve this answer
    
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
add comment

See this related StackOverflow post.

complete 'your_command' 'p/*/`echo list_of_your_options`/'
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.