Python argparse value range help message appearance

前端 未结 4 579
挽巷
挽巷 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 07:55

    You can customize action, e.g:

    #!/usr/bin/env python
    import argparse
    
    
    class Range(argparse.Action):
        def __init__(self, minimum=None, maximum=None, *args, **kwargs):
            self.min = minimum
            self.max = maximum
            kwargs["metavar"] = "[%d-%d]" % (self.min, self.max)
            super(Range, self).__init__(*args, **kwargs)
    
        def __call__(self, parser, namespace, value, option_string=None):
            if not (self.min <= value <= self.max):
                msg = 'invalid choice: %r (choose from [%d-%d])' % \
                    (value, self.min, self.max)
                raise argparse.ArgumentError(self, msg)
            setattr(namespace, self.dest, value)
    
    
    norse = argparse.ArgumentParser('Norse')
    norse.add_argument('--threshold', required=False, type=int, min=0, max=100,
                       action=Range,
                       help='Threshold [%(min)d-%(max)d] denoting at what threat \
                             level to provide additional data on an IP address. \
                             Default is %(default)s.', default=49)
    args = norse.parse_args()
    print args
    

    Test it:

    ~: user$ ./test.py --threshold 10
    Namespace(threshold=10)
    ~: user$ ./test.py --threshold -1
    usage: Norse [-h] [--threshold [0-100]]
    Norse: error: argument --threshold: invalid choice: -1 (choose from [0-100])
    ~: user$ ./test.py -h
    usage: Norse [-h] [--threshold [0-100]]
    
    optional arguments:
      -h, --help           show this help message and exit
      --threshold [0-100]  Threshold [0-100] denoting at what threat level to
                           provide additional data on an IP address. Default is
                           49.
    

提交回复
热议问题