Can optparse do dependencies?

Raymond Hettinger python at rcn.com
Sat Feb 25 15:32:27 EST 2006


[Bob]
> I'd like to setup command line switches that are dependent on other
> switches, similar to what rpm does listed below. From the grammar below
> we see that the "query-options" are dependent on the query switch,
> {-q|--query}. Can "optparse" do this or do I have to code my own
> "thing"? Thanks.
>
> QUERYING AND VERIFYING PACKAGES:
>        rpm {-q|--query} [select-options] [query-options]
> ...
>    query-options
>         [--changelog] [-c,--configfiles] [-d,--docfiles] [--dump]
>         [--filesbypkg] [-i,--info] [--last] [-l,--list]
>         [--provides] [--qf,--queryformat QUERYFMT]
>         [-R,--requires] [--scripts] [-s,--state]
>         [--triggers,--triggerscripts]

The optparse module doesn't have native support for switch
dependencies; however, it could likely be done with multiple passes.
The parse_args() takes an args list as an argument.  Make first pass
that captures your main query switches, then run another parser on a
slice of the args list.

For example, capture the main switches on a first pass over the full
argument list (catching all possible main switches and treating
everything else as a catchall).  Given, args=['-ql', '--changelog',
'-d', '-c'], parse out the --changelog and then call another parser
with args=['-d', '-c'].

This functionality seems useful enough to build into the tool directly,
so do consider putting a feature request on SourceForge (and assign to
Greg Ward).


Raymond




More information about the Python-list mailing list