Python: don't display "selections" using argparse

With argparse , I have the following line:

parser.add_argument("-p", "--parameter", type=str, default=None, nargs='+', help="some option", choices=allValues.keys() ) 

The received help message shows all the values ​​in allValues :

-p {a, b, c, d, e, f, g, h, i, l, m; a, b, c, d, e, f, g, h, i, l, m} [{a, b, c, d, e, f, g, h, i, l, m} ...] , -parameter {a, b, c, d, e, f, g, h, i, l, m; a, b, c, d, e, f, g, h, i, l, m} [{a, b, c, d, e, f, g, h, i, l, m; a, b, c, d, e, f, g, h, i, l, m} ...] some option

Is it possible to remove {a ,b ,c , d, e, f, g, h, i, l, m; a ,b ,c , d, e, f, g, h, i, l, m} {a ,b ,c , d, e, f, g, h, i, l, m; a ,b ,c , d, e, f, g, h, i, l, m} above and just display the name this parameter and help message?

+4
source share
2 answers

Use the metavar argument ::

 parser.add_argument("-p", "--parameter", type=str, default=None, nargs='+', help="some option", choices=allValues.keys(), metavar='PARAMETER' ) 

This will give:

 -p PARAMETER, --parameter PARAMETER some option 

If you don't want to show meta variables, you can consider passing '' to metavar . Otherwise, I believe you will have to create your own formatting classes and pass them to ArgumentParser .

+9
source

On lesspass, we used both metavar and a custom type to control metavar and an error message was displayed:

  • Use metavar to get more metavar help message
  • Use a custom type to control the error message.

Output

Error message

 env ❯ python3 lesspass/core.py site login masterpassword --lowercase --digits --length 2 usage: lesspass SITE [LOGIN] [MASTER_PASSWORD] [OPTIONS] core.py: error: argument -L/--length: 2 is out of range, choose in [5-35] 

Help message

 env ❯ python3 lesspass/core.py --help … -L [5-35], --length [5-35] password length (default: 16, min: 5, max: 35) … 

How to do it?

Custom type

 def range_type(value_string): value = int(value_string) if value not in range(5, 35+1): raise argparse.ArgumentTypeError("%s is out of range, choose in [5-35]" % value) return value 

add_argument declaration

 parser.add_argument( "-L", "--length", default=16, choices=range(5, 35+1), type=range_type, help="password length (default: 16, min: 5, max: 35)", metavar='[5-35]' 

)

0
source

Source: https://habr.com/ru/post/1492124/


All Articles