Re: Ignore Options

"Mark E. Hamilton" <[email protected]> Wed, 20 Feb 2008 09:26:16 -0700
Newsgroups gmane.comp.python.optik.user
Message-ID <[email protected]>
Alec Solway wrote:
> Is there a way to have optparse ignore unrecognized options instead of
> bailing out?

If it did then you couldn't tell if the user passed an invalid option.

However, a little testing shows that optparse does correctly handle the 
standard '--' option, which means to stop processing options at that 
point. Everything following that option is assumed to be a parameter, 
and will be placed in the args element of the tuple returned by 
parse_args().

So, for instance, with something like this:

#!/bin/env python
import optparse
p = optparse.OptionParser()
p.add_option("-t", action="append", type="string", dest="test")
opt, args = p.parse_args()
print 'opt :', opt
print 'args:', args

Would fail (as it should) if '-a' was passed before '--'

sahp7635% ./test2.py -a
usage: test2.py [options]

test2.py: error: no such option: -a

or would produce this if it was passed after.

sahp7635% ./test2.py arg -- -a
opt : {'test': None}
args: ['arg', '-a']


or this (with a more fully populated command line.)

sahp7635% ./test2.py -t something -- param -a
opt : {'test': ['something']}
args: ['param', '-a']


-- 
----------------
Mark E. Hamilton
Orion International Technologies, Inc.
Sandia National Laboratory, NM.
505-844-7666


-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/