[issue4256] optparse: provide a simple way to get a programmatically useful list of options
Andy Buckley
report at bugs.python.org
Mon Apr 5 17:44:33 CEST 2010
Andy Buckley <andy at insectnation.org> added the comment:
Thanks for the pointers to both of these... I wasn't aware of either. I see argparse has been recently approved for Python stdlib inclusion, too: http://www.python.org/dev/peps/pep-0389/ Congratulations!
As far as I can tell, genzshcomp is parsing the output of the help command to reverse-engineer what the allowed flags should be. Assuming that only one space occurs between the arg and its metavar, this should work 99% or the time... I'm not sure if there is any attempt to be clever when the formatting is ambiguous. But given that the opt parser already contains the structured information, life can be made easier by writing out a more readily parseable format.
Here's an example bash parser function and its usage, for a further-simplified form of the above format where each arg (long or short) gets a line of its own and the arguments are indicated by a separate word as in the current output:
Example input:
$ foo --help-options
#OPTPARSE_FORMAT 0
--version
-h
--help
-r REGEXP
--regexp REGEXP
-s N
--start N
-e M
--end M
-f FILE
--file FILE
and the parser/completion functions:
function _optparse_getargs() {
local opts cur prev
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
PREVIFS=$IFS
IFS=$'\n'
for line in `$1 --help-options | egrep '^-'`; do
opt=`echo $line | sed 's/^\(-[^ ]\+\).*$/\1/'`
argeq=`echo $line | sed 's/^--[^ ]\+ \([A-Za-z0-9]*\)$/=/'`
if [[ $argeq != "=" ]]; then argeq=""; fi
opts="$opts $opt$argeq";
done
IFS=$PREVIFS
unset PREVIFS
opts=`echo $opts | sed -e 's/^ *//' -e 's/ *$//'`
if [[ ${cur} == -* ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
if test -n "$COMPREPLY"; then
return 0
fi
fi
return 0
}
function _foo() {
_optparse_getargs foo
return 0
}
complete -F _foo -o default foo
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue4256>
_______________________________________
More information about the Python-bugs-list
mailing list