On Sun, 19 Apr 2009 14:45:45 +0100, David Stanek <dsta...@dstanek.com> wrote:

On Thu, Apr 16, 2009 at 10:05 AM, sapsi <saptarshi.g...@gmail.com> wrote:
Hello,
Im using optparse and python 2.6 to parse some options, my commandline
looks like

prog [options] start|stop extra-args-i-will-pas-on

The options are --b --c --d

The extra options are varied are are passed onto another program e.g --
quiet --no-command , my program doesnt care what these are but instead
passes them onto another program.

I know these will always follow start|stop.

However optparse tries to process them and throws an exception - how
can i prevent this without placing all the extra-args in quotes.



In Linux (maybe in Windows) you can tell an application to stop
processing args by using '--'. Given this code:
    import sys
    from optparse import OptionParser
    op = OptionParser()
    op.add_option('--a', dest='a', action='store_true', default=False)
    op.add_option('--b', dest='b', action='store_true', default=False)
    opts, args = op.parse_args(sys.argv)
    print 'opts:', opts
    print 'args:', args

Here is an example use:
    eee0:~% python junk.py --a -- --c
    {'a': True, 'b': False}
    ['junk.py', '--c']



It's only a convention, but it is one that optparse follows, so it'll
work quite happily on any platform.  The info on it is buried in the
documentation, in an example of options with a variable number of
arguments:

"""
And you have to deal with certain intricacies of conventional Unix
command-line parsing that optparse normally handles for you. In
particular, callbacks should implement the conventional rules for
bare "--" and "-" arguments:

* either "--" or "-" can be option arguments
* bare "--" (if not the argument to some option): halt command-line
     processing and discard the "--"
* bare "-" (if not the argument to some option): halt command-line
     processing but keep the "-" (append it to parser.largs)
"""

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to