从命令行选项创建数组(python :: optparse)

时间:2011-10-06 07:35:12

标签: python arrays command-line-arguments optparse

有一个python脚本从命令行读取基准名称,如下所示:

-b benchname1

此操作的代码是:

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!"

我想要做的是为此命令行创建一个基准数组:

-b benchname1 benchname2

所以“进程”应该是一个数组:

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

有什么建议吗?

感谢名单

3 个答案:

答案 0 :(得分:7)

如果你有Python 2.7+,你可以使用argparse模块而不是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

脚本的示例运行 -

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

答案 1 :(得分:4)

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

答案 2 :(得分:1)

您可以接受以逗号分隔的列表,例如

-b benchname1,benchname2

然后处理代码中的逗号分隔列表以生成数组 -

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