Passing all extra commandline arguments to python program, Optparse raises exception

David Stanek dstanek at dstanek.com
Sun Apr 19 09:45:45 EDT 2009


On Thu, Apr 16, 2009 at 10:05 AM, sapsi <saptarshi.guha at 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']


-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek



More information about the Python-list mailing list