开发者

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':
 开发者_Go百科 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


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']


    self.opt_parser.add_argument('-s', '--skip',
        default=[],
        type=str,
        help='A name of a project or build group to skip. Can be repeated to skip multiple projects.',
        dest='skip',
        action='append')


You can accept a comma separated list for benchmark names like this

-b benchname1,benchname2

Then process the comma separated list in your code to generate the array -

bench_map = {'benchname1': Mybench.b1,
             'benchname2': Mybench.b2,
            }
process = []

# Create a list of benchmark names of the form ['benchname1', benchname2']
benchmarks = options.benchmark.split(',')

for bench_name in benchmarks:
    process.append(bench_map[bench_name])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜