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

There is a python script that reads the name of the test from the command line as follows:

-b benchname1 

Code for this offer:

 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 create an array of benchmarks for this command line:

 -b benchname1 benchname2 

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

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

Are there any suggestions for this?

Thanx

+4
source share
3 answers

If you have Python 2.7+, you can use argparse 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 

Script run example -

 $ 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'] 
+7
source
  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') 
+4
source

You can accept a comma-separated list for test names such as

 -b benchname1,benchname2 

Then process the comma separated list in your code to generate an 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]) 
+1
source

All Articles