【发布时间】:2014-08-12 22:39:09
【问题描述】:
这个问题可能有一个明显的答案,但我已经看了一段时间没有弄清楚。这是一些使用 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?
【问题讨论】:
-
我敢打赌
args的值会有所不同。search是布尔值True,schema是字符串'True'。