从一个命令行选项创建一个数组(蟒蛇:: optparse) [英] creating an array from a command line option (python::optparse)
本文介绍了从一个命令行选项创建一个数组(蟒蛇:: optparse)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个python脚本从这样的读取命令行的基准名称:
There is a python script which reads a benchmark name from command line like this:
-b benchname1
在code这个perpose是:
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?
感谢名单
推荐答案
如果你有Python的2.7+,你可以使用的 argparse 模块,而不是optparse。
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']
这篇关于从一个命令行选项创建一个数组(蟒蛇:: optparse)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文