Search code examples
pythonpython-2.6optparse

How to loop through optparse.OptionGroup in Python


I am trying to loop through a certain group of parameters ('-p' only). I declare them as follows in the terminal: python program.py -p paramOne paramTwo. My program output is only paramOne and I do not understand why. My goal is to get the following output:

paramOne
paramTwo

Can anyone tell me where the error in my code is?

Here is the code:

# Parcing definitions
parser = optparse.OptionParser()
groupParam = optparse.OptionGroup(parser, 'Output handling')
parser.add_option('-q', '--quiet', action='store_false', dest='verbose', default=True,
                help=('don\'t print status messages to stdout'))
groupParam.add_option('-p', '--parameters', action='store', dest='paramNum', type='string', 
                help=('specify number of parameters (Optional)'))

parser.add_option_group(groupParam)

(options, args) = parser.parse_args()


for groupParam1 in groupParam.option_list:
    print getattr(options, groupParam1.dest)

P.S. I am running Python 2.6.6


Solution

  • If you don't specify nargs, it uses 1 as a default value; consuming only one positional argument.

    Specify nargs=2 to get 2 values:

    groupParam.add_option(
        '-p', '--parameters', action='store', dest='paramNum', type='string',
        nargs=2,  # <---
        help=('specify number of parameters (Optional)')
    )
    

    According to documentation:

    How many arguments of type type should be consumed when this option is seen. If > 1, optparse will store a tuple of values to dest.

    so, the last loop should be modified to check tuple to print as you wanted:

    for groupParam1 in groupParam.option_list:
        values = getattr(options, groupParam1.dest)
        if isinstance(values, tuple):
            for value in values:
                print(value)