Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my argparse show default values?

According to this question, this script called "parse_fail.py" should print default=1 when I type:

python parse_fail.py --help 

on the command line, but it doesn't. Why not?

#parse_fail.py

import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--test", type=int, dest='test', default=1)
parser.parse_args()
args_dict = vars(parser.parse_args())
locals().update(args_dict)
print test

When I run this script I get:

$ python parser_fail.py  --help
usage: parser_fail.py [-h] [--test TEST]

optional arguments:
  -h, --help   show this help message and exit
  --test TEST

EDIT: added output of the script.

like image 819
capybaralet Avatar asked Apr 08 '16 01:04

capybaralet


Video Answer


1 Answers

Apparently you need to include a non-empty help string.

This works:

import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--test", type=int, dest='test', help="WHY NO DEFAULT???", default=1)
parser.parse_args()
args_dict = vars(parser.parse_args())
locals().update(args_dict)
print test



$ python parser_fail.py -h
usage: parser_fail.py [-h] [--test TEST]

optional arguments:
  -h, --help   show this help message and exit
  --test TEST  WHY NO DEFAULT??? (default: 1)
like image 52
capybaralet Avatar answered Oct 22 '22 13:10

capybaralet