Python argparse value range help message appearance

前端 未结 4 583
挽巷
挽巷 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 08:04

    Use the metavar parameter of add_argument().

    For example:

    norse = parser.add_argument_group('Norse')
    norse.add_argument('-n', '--norse', required=False, help='Run the Norse IPViking scan.', action='store_true')
    norse.add_argument('--threshold', required=False, type=int, choices=range(0,101),
                       metavar="[0-100]", 
                       help='Threshold (0-100) denoting at what threat level to provide additional data on an IP \
                            address. Default is 49.', default=49)
    

    Test:

    from argparse import ArgumentParser
    
    norse = ArgumentParser()
    
    norse.add_argument('-n', '--norse', required=False, help='Run the Norse IPViking scan.', action='store_true')
    norse.add_argument('--threshold', required=False, type=int, choices=range(0,101), metavar="[0-100]", help='Threshold (0-100) denoting at what threat level to provide additional data on an IP address. Default is 49.', default=49)
    
    
    norse.print_help()
    

    Results

    usage: -c [-h] [-n] [--threshold [0-100]]
    
    optional arguments:
      -h, --help           show this help message and exit
      -n, --norse          Run the Norse IPViking scan.
      --threshold [0-100]  Threshold (0-100) denoting at what threat level to
                           provide additional data on an IP address. Default is
                           49.
    

提交回复
热议问题