python - When does argparse not complain about this missing argument? -
there obvious reply question, i've looked @ bit without figuring out. old python code using argparse. haven't used argparse recently, may have forgotten nuance.
#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 parser "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 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) let invoke as:
python test.py usage: test.py [-h] {crossval} ... test.py: error: few arguments now as
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 help message , exit -n samplenum, --samplenum samplenum number of samples crossvalidation on (default: none) -p, --permuted permuted dataset (default: false) -s, --search model search (default: false) now as
python test.py crossval -n 1 -s true schema true samplenum 1 permuted false search true question: why argparse not complain missing schema argument, , why set true?
at glance, -s alternative boolean - presence implies true , requires no argument. when python test.py crossval -n 1 -s true, true gets parsed beingness schema argument since -s switch doesn't require value.
this much can in fact gleaned usage string in help text:
usage: test.py crossval [-h] [-n samplenum] [-p] [-s] schema the [-s] indicates it's nullary option, unlike -n listed [-n samplenum] since requires argument (samplenum).
edit:
this behavior stated in python 2.7 documentation argparse, infer version using in illustration since using statement- rather function-form of print. quote section 15.4.3.2:
'store_true' , 'store_false' - these special cases of 'store_const' using storing values true , false respectively. in addition, create default values of false , true respectively.
python argparse
No comments:
Post a Comment