【问题标题】:Sorting the command line arguments entered by user in our predefined way以我们预定义的方式对用户输入的命令行参数进行排序
【发布时间】:2014-09-02 04:27:16
【问题描述】:

我已经使用optparse 为我的python 脚本定义了一些选项。在我的脚本中,用户以任何顺序输入命令行参数,但我想以我预定义的方式进行排序。假设用户输入以下参数:

scriptname -g gvalue -n nvalue -s svalue -k kvalue -e evalue

当用户以任意顺序输入上述参数时,我想按如下方式排序:

-s svalue -g gvalue -k kvalue -n nvalue -e evalue

最终我随时都需要上面的订单。

【问题讨论】:

  • 我不明白; opt parse 将按名称为您提供参数,而不管原始顺序如何。
  • 您在 optparse 配置中使用不同于“存储操作”的操作? (即“回调”)
  • 为什么需要对它们进行排序?您可以对它们进行排序,但这确实是不必要的。此外,argparse,不推荐使用 optparse。
  • 另请参阅this post,了解为什么使用argparse 而不是optparse

标签: python optparse


【解决方案1】:

可能有更好的方法来获得你想要的东西。你不应该这样做。但这是解决方法:

我将使用argparse,因为optparse 已被弃用。 如果用户没有为该参数指定值,此代码将显示 None

## directory user$ ./argparse_ex.py -s foo -g bar -k quox -n woo -e testing123

import argparse
parser = argparse.ArgumentParser(description='Sorted Arguments')
parser.add_argument('-s', help='I will be printed if the user types --help')
parser.add_argument('-g', help='I will be printed if the user types --help')
parser.add_argument('-k', help='I will be printed if the user types --help')
parser.add_argument('-n', help='I will be printed if the user types --help')
parser.add_argument('-e', help='I will be printed if the user types --help')

args = vars(parser.parse_args())

sorted_args = [args['s'], args['g'], args['k'], args['n'], args['e']]
print sorted_args

## ['foo', 'bar', 'quox', 'woo', 'testing123']

argparse documentation here

【讨论】:

    【解决方案2】:

    假设optparse 是用每个值的命令定义的,例如:

    parser.add_option("-k", action="store", type="string", dest="kvalue")
    

    并执行为:

    (options, args) = parser.parse_args()
    

    然后options.kvalue 将包含-k 的相关用户输入参数。然后就可以生成按顺序排列的序列了:

    ( getattr(options,name) for name in ('svalue', 'gvalue', 'kvalue', 'nvalue', 'evalue') )
    

    或者,对原始argv 进行字符串比较也可以在不使用optparse 的情况下实现相同的效果。

    【讨论】:

      猜你喜欢
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 2015-03-26
      相关资源
      最近更新 更多