Python argparse value range help message appearance

前端 未结 4 589
挽巷
挽巷 2021-02-08 07:46

I have an argument for a program that is an integer from 1-100 and I just don\'t like the way that it shows up in the -h help message when using argparse (it literally lists 0,

4条回答
  •  面向向阳花
    2021-02-08 07:59

    With a custom type, it is easier to control the error message (via the ArgumentTypeError). I still need the metavar to control the usage display.

    import argparse
    
    def range_type(astr, min=0, max=101):
        value = int(astr)
        if min<= value <= max:
            return value
        else:
            raise argparse.ArgumentTypeError('value not in range %s-%s'%(min,max))
    
    parser = argparse.ArgumentParser()
    norse = parser.add_argument_group('Norse')
    ...
    norse.add_argument('--range', type=range_type, 
        help='Value in range: Default is %(default)s.',
        default=49, metavar='[0-101]')
    parser.print_help()
    print parser.parse_args()
    

    producing:

    2244:~/mypy$ python2.7 stack25295487.py --ran 102
    usage: stack25295487.py [-h] [-n] [--threshold [0:101]] [--range [0-101]]
    
    optional arguments:
      -h, --help           show this help message and exit
    
    Norse:
      ...
      --range [0-101]      Value in range: Default is 49.
    usage: stack25295487.py [-h] [-n] [--threshold [0:101]] [--range [0-101]]
    stack25295487.py: error: argument --range: value not in range 0-101
    

    I could use functools.partial to customize the range values:

    type=partial(range_type, min=10, max=90)
    

提交回复
热议问题