OptionParser python module - multiple entries of same variable?

jduncan picture jduncan · May 3, 2010 · Viewed 7.6k times · Source

I'm writing a little python script to get stats from several servers or a single server, and I'm using OptionParser to parse the command line input.

#!/usr/bin/python

import sys
from optparse import OptionParser
...
parser.add_option("-s", "--server", dest="server", metavar="SERVER", type="string", 
                  help="server(s) to gather stats [default: localhost]")
...

my GOAL is to be able to do something like

#test.py -s server1 -s server2

and it would append both of those values within the options.server object in some way so that I could iterate through them, whether they have 1 value or 10.

Any thoughts / help is appreciated. Thanks.

Answer

mg. picture mg. · May 3, 2010
import optparse

parser = optparse.OptionParser()
parser.add_option('-t', '--test', action='append')

options, args = parser.parse_args()
for i, opt in enumerate(options.test):
    print 'option %s: %s' % (i, opt)