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

Peter Otten __peter__ at web.de
Fri Mar 12 16:15:08 EST 2004


Sam Smith wrote:

> Usage Scenario:
> 
> I am implementing a multi-level commandline program.  On windows
> platform similar to "net /?" command which in turn has "net use /?",
> "net computer /?" etc commandlines.
> 
> Some of my commandlines share the same option-arg, but the default
> value to be associated with each of them is different.  In one of the
> commandlines I was trying to detect if the user has specified the
> option or not and if not assign a different value to the option.

I normally don't advocate code duplication, but in this case I'd either
specialcase

if specialcommandline:
    parser.add_option(special option)
else:
    parser.add_option(normal option)

or completely separate the parsers for the two differing scenarios.
 
> Irrespective of the usage scenario, I believe that it is important to
> give the module user the ability to find out whether an option has
> been specified or not by the user.

Irrespective of the usage scenario - you can't be serious here.
 
> Some suggestions:
> 
> * Maybe a method can be added to the option class, isSpecified()
>   which will return True if the option is found on commandline
>   and optparse has read it or False if the option is not found
>   on the commandline.
> 
> * Add ability to query the Values instance which is returned by
>   parse_args

My doubts not withstanding, here's how to achieve the desired (I think)
behaviour in a few lines - not tested beyond what you see as I will hardly
ever use it myself:

import sets
import optparse as op

class Values(op.Values):
    def __init__(self, defaults):
        op.Values.__init__(self, defaults)
        self.specified = sets.Set([])

    def __setattr__(self, name, value):
        self.__dict__[name] = value
        if hasattr(self, "specified"):
            self.specified.add(name)


def test(args):
    p = op.OptionParser()
    p.add_option("-f", dest="filename", default="tmp.txt")
    v = Values(p.defaults)
    p.parse_args(args, v)
    if "filename" in v.specified:
        info = "specified:"
    else:
        info = "using default:"
    print info, v.filename

test(["-f", "other.txt"])
test(["-f", "tmp.txt"])
test([])

Peter






More information about the Python-list mailing list