Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OptionParser python module - multiple entries of same variable?

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.

like image 402
jduncan Avatar asked May 03 '10 04:05

jduncan


People also ask

Is Optparse deprecated?

optparse is deprecated since python 3.2 and is not developed anymore.

What is import Optparse in Python?

optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser , populate it with options, and parse the command line.

What is Optparse in Ruby?

OptionParser is a class for command-line option analysis. It is much more advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented solution.


1 Answers

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)
like image 133
mg. Avatar answered Oct 21 '22 05:10

mg.