Optparse: Detecting if option or option-arg is specified or not

Peter Otten __peter__ at web.de
Thu Mar 11 23:48:01 CET 2004


Sam Smith wrote:

> I am using optparse for the commandline parsing for my programs.  I
> was wondering if it is possible to detect if an option or option-arg
> has been specified on the commandline by the user or not. Please do
> not suggest default value solutions.

What's wrong with default values?
Anyway, here's the hasattr() approach:

>>> p = optparse.OptionParser()
>>> p.add_option("-x", action="store_true")
<optparse.Option instance at 0x403a1fcc>
>>> class NS: pass
...
>>> values = NS()
>>> p.parse_args([], values)
(<__main__.NS instance at 0x402c3f6c>, [])
>>> hasattr(values, "x")
False
>>> p.parse_args(["-x"], values)
(<__main__.NS instance at 0x402c3f6c>, [])
>>> hasattr(values, "x")
True
>>>

Peter



More information about the Python-list mailing list