To understand what is going on here, let's see what this bash function does:
COMPREPLY=( $( \ COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \ COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \ OPTPARSE_AUTO_COMPLETE=1 $1 ) )
See $1 at the end? This means that it actually calls the Python file that we want to execute, with the special environment variables set! To keep track of what is happening, let's prepare a little script to capture what optcomplete.autocomplete does:
#!/usr/bin/env python2 import os, sys import optparse, optcomplete from cStringIO import StringIO if __name__ == '__main__': parser = optparse.OptionParser() parser.add_option('-s', '--simple', action='store_true', help="Simple really simple option without argument.") parser.add_option('-o', '--output', action='store', help="Option that requires an argument.") opt = parser.add_option('-p', '--script', action='store', help="Option that takes python scripts args only.") opt.completer = optcomplete.RegexCompleter('.*\.py')
This gives us the following when we try to autofill it:
$ ./test.py [tab] called with args: ['./test.py'] ... COMP_CWORD: 1 COMP_LINE: ./test.py COMP_POINT: 10 COMP_WORDS: ./test.py ... OPTPARSE_AUTO_COMPLETE: 1 ... autocomplete tried to exit with status 1 autocomplete tried to write to STDOUT: -o -h -s -p
So optcomplete.autocomplete just reads the environment, prepares the matches, writes them to STDOUT and completes. The result -o -h -s -p --script --simple --help --output then placed into the bash array ( COMPREPLY=( ... ) ) and returned to bash to present the choice to the user. There was no magic :)
Niklas B. Mar 05 '12 at 17:52 2012-03-05 17:52
source share