【问题标题】:creating an array from a command line option (python::optparse)从命令行选项创建一个数组 (python::optparse)
【发布时间】:2011-12-02 01:14:21
【问题描述】:

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

-b benchname1

这个perpose的代码是:

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

对此有什么建议吗?

感谢

【问题讨论】:

    标签: python arrays command-line-arguments optparse


    【解决方案1】:

    如果你有 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']
    

    【讨论】:

      【解决方案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')
      

      【讨论】:

      • 不如将其用作'my.py --skip a --skip b'
      • 我使用了“--skip benchname1 --skip benchname2”,但出现此错误:“AttributeError: Values instance has no attribute 'benchmark'”。它指向的行是“if options.benchmark == 'benchname1':” 你的意思是我用'-s'替换'-b'吗?
      【解决方案3】:

      您可以接受以逗号分隔的基准名称列表

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

      【讨论】:

      • 我应该删除我的“if, elif, else”吗?
      • 好的,我找到了。不需要“bench_map”。我通过“,”分隔列表传递选项,然后按照您所说的进行拆分。最后我用“process.append(bench_name)”将它们附加到处理中,谢谢:)
      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多