Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an array from a command line option (python::optparse)

There is a python script which reads a benchmark name from command line like this:

-b benchname1

The code for this perpose is:

import optparse
import Mybench
parser = optparse.OptionParser()
# Benchmark options
parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.")
if options.benchmark == 'benchname1':
  process = Mybench.b1
elif options.benchmark == 'benchname2':
  process = Mybench.b2
else:
  print "no such benchmark!"

what I want to do is to create a an array of benchmarks for this command line:

-b benchname1 benchname2

So the "process" should be an array that is:

process[0] = Mybench.b1
process[1] = Mybench.b2

Is there any suggestion for that?

Thanx

like image 230
mahmood Avatar asked Dec 13 '22 08:12

mahmood


1 Answers

If you have Python 2.7+, you can use argparse module instead of optparse.

import argparse

parser = argparse.ArgumentParser(description='Process benchmarks.')
parser.add_argument("-b", "--benchmark", default=[], type=str, nargs='+',
                    help="The benchmark to be loaded.")

args = parser.parse_args()
print args.benchmark

Sample run of the script -

$ python sample.py -h
usage: sample.py [-h] [-b BENCHMARK [BENCHMARK ...]]

Process benchmarks.

optional arguments:
  -h, --help            show this help message and exit
  -b BENCHMARK [BENCHMARK ...], --benchmark BENCHMARK [BENCHMARK ...]
                        The benchmark to be loaded.

$ python sample.py -b bench1 bench2 bench3
['bench1', 'bench2', 'bench3']
like image 119
ronakg Avatar answered Jan 22 '23 17:01

ronakg