argument problem in optparse

John O'Hagan research at johnohagan.com
Fri Mar 20 22:37:50 EDT 2009


On Fri, 20 Mar 2009, Qian Xu wrote:
> Hi All,
>
> I have a problem with OptParse.
> I want to define such an arugument. It can accept additional value or no
> value.
>
> "myscript.py --unittest File1,File2"
> "myscript.py --unittest"
>
> Is it possible in OptParse? I have tried several combination. But ...


For reasons explained in the optparse documentation, it doesn't directly 
support options which take an arbitrary number of arguments, to do that you 
use a callback function like this:


import sys
from optparse import OptionParser

def my_callback(option, opt_str, value, parser):
    "Accept options which take any number of arguments"
    
    value = []
    for item in parser.rargs:
        if item[0] == '-':    #stop at next option
            break
        value.append(item)
    if not value:
        value = True
    setattr(parser.values, option.dest, value)
        
parser = OptionParser()
parser.add_option("--unittest", action="callback",
    callback=my_callback, dest="unittest")

options = parser.parse_args(sys.argv[1:])[0]

Now if you invoke myscript.py with --unittest, options.unittest will 
be 'True', with --unittest File1 File2, it will be ['File1', 'File2'], etc..  

This doesn't work with the comma-separated argument example you gave, but it 
could be made to; I hope the above gets you started. There are callback 
examples in the optparse docs too.

Regards,

John



More information about the Python-list mailing list