Interleaved commands and options with optparse?
David Goodger
goodger at python.org
Wed Jan 22 22:11:03 EST 2003
Magnus Lie Hetland wrote:
> Now... I'd like to interleave "commands" (i.e. simple arguments) with
> my options, as in, e.g., cvs (or distutils, for that matter). For
> example:
>
> python myscript.py --globaloption command --commandoption
>
> I'd like the semantics of the options to depend on where they are
> placed, e.g. before or after a command etc. (I might have global and
> command-specific switches with the same single-letter abbreviation but
> with different meanings -- as in cvs.)
Set up an OptionParser instance for the global options, and be sure to set
the allow_interspersed_args attribute to 0/False. Then parse your arglist.
The global options will be parsed, and the first item of the remaining
arglist will be your subcommand. Set up a new OptionParser instance for
that subcommand, and parse the remainder of the command line.
There's no magic trick to it, just straightforward processing.
--
David Goodger http://starship.python.net/~goodger Projects:
* Python Docutils: http://docutils.sourceforge.net/
(includes reStructuredText: http://docutils.sf.net/rst.html)
* The Go Tools Project: http://gotools.sourceforge.net/
More information about the Python-list
mailing list