什么时候argparse没有抱怨这个缺失的论点?

时间:2014-06-22 23:08:51

标签: python argparse

这个问题可能有一个明显的答案,但是我已经看了一会儿而没有搞清楚。这是一些使用argparse的旧Python代码。我最近没有使用过argparse,所以我可能已经忘记了一些细微差别。

#test.py

def load_crossval_dataset(args):
    schema, samplenum, permuted, search = args.schema, args.samplenum, args.permuted, args.search

    print "schema", schema
    print "samplenum", samplenum
    print "permuted", permuted
    print "search", search

import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
subparsers = parser.add_subparsers()

# create the parser for the "crossval" command                                                                                                                 
parser_crossval = subparsers.add_parser('crossval', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser_crossval.add_argument('schema', help='name of schema')
parser_crossval.add_argument("-n", "--samplenum", action="store", type=int, dest="samplenum", help="number of samples to do crossvalidation on")
parser_crossval.add_argument("-p", "--permuted", action="store_true", dest="permuted", help="permuted dataset", default=False)
parser_crossval.add_argument("-s", "--search", action="store_true", dest="search", help="model search", default=False)
parser_crossval.set_defaults(func=load_crossval_dataset)

args = parser.parse_args()
args.func(args)

让我们将其称为:

python test.py

usage: test.py [-h] {crossval} ...
test.py: error: too few arguments

现在为

python test.py crossval -h

usage: test.py crossval [-h] [-n SAMPLENUM] [-p] [-s] schema

positional arguments:
  schema                name of schema

optional arguments:
  -h, --help            show this help message and exit
  -n SAMPLENUM, --samplenum SAMPLENUM
                        number of samples to do crossvalidation on (default: None)
  -p, --permuted        permuted dataset (default: False)
  -s, --search          model search (default: False)

现在为

python test.py crossval -n 1 -s True                                                                                                                         

schema True
samplenum 1
permuted False
search True

问题:为什么argparse没有抱怨丢失的schema参数,为什么将它设置为True

2 个答案:

答案 0 :(得分:1)

乍一看,-s选项是布尔值 - 因此它的存在意味着True,它不需要参数。因此,当您说python test.py crossval -n 1 -s True时,True会被解析为架构参数,因为-s开关不需要值。

事实上,这可以从帮助文本中的用法字符串中收集:

usage: test.py crossval [-h] [-n SAMPLENUM] [-p] [-s] schema

[-s]表示它是一个无效的选项,不像-n列出的[-n SAMPLENUM],因为它需要一个参数(SAMPLENUM)。

修改

Python 2.7 Documentation for argparse中说明了这种行为,我推断这是您在示例中使用的版本,因为您使用的是print的语句而不是函数形式。引用第15.4.3.2节:

  

'store_true'和'store_false' - 这些是'store_const'的特殊情况,用于分别存储值True和False。此外,它们分别创建False和True的默认值。

答案 1 :(得分:1)

选项-s不接受论证(store_conststore_truestore_false行动不接受争论 - 这可能需要在文档)。所以在python test.py crossval -n 1 -s True中,参数Truecrossval的位置参数,而不是-s的参数;因此它是schema的价值。

python test.py crossval -n 1 -s正确地抱怨test.py crossval缺少参数。