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

给你一囗甜甜゛ 提交于 2019-12-01 21:41:04

问题


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


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/7671383/creating-an-array-from-a-command-line-option-pythonoptparse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!