views:

393

answers:

3

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.

+2  A: 

You could try to check out argparse. It provides "nargs" parameter meaning you would be able to do something along

#test.py -s server1 server2

I know that's not exactly what requested but it might be a decent compromise without too much hassle. :)

bebraw
+2  A: 

Could be easier to accept a comma-separated list of servers:

# test.py -s server1,server2

and split the value within your script.

harto
+4  A: 
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)
mg
That's what I thought would work, as well.However I get this error:AttributeError: 'str' object has no attribute 'append'when I give a string option that action.
jduncan
@jduncan: Are you sure? I just tried it and again it works as expected.
mg
This fails for me (Python 2.6) if I don't specify any options -- options.test is None and cannot be enumerated
Marius Gedminas
Other than that, this code works with Python 2.4, 2.5 and 2.6
Marius Gedminas
@jduncan: I can reproduce the error if I do `parser.add_option(..., default='a_string', action='append')`, but that is incorrect. In fact, if you do that and not provide an option, you'll end up iterating over all the characters. Plus, specifying anything would only append, so you could never override the default server. Don't do it; if you need a default, do `enumerate(options.test or ['default'])`.
Marius Gedminas