Optparse: using the arg variable in a callback action does not mean that additional parameters are needed

I implemented in my python code a callback for variable arguments, similar to what can be found here:
hxxp: //docs.python.org/library/optparse.html#callback-example-6-variable-arguments

Adding an option as follows:

parser.add_option("-c", "--callback", dest="vararg_attr", action="callback", callback=vararg_callback)

The problem is that for the user there is no indication of the need for additional input:

Options:  
    -h, --help      show this help message and exit  
    -c, --callback

Is there a way to change the use of optparse so that the use prints something like:

-c=LIST, --callback=LIST

Thank you for your help! Ben

+3
source share
3 answers

monkeypatching , , . , .

from optparse import OptionParser, Option

# Complete hack.
Option.ALWAYS_TYPED_ACTIONS += ('callback',)

def dostuff(*a):
    pass

parser = OptionParser()
parser.add_option("-c",
                  "--callback",
                  dest="filename",
                  action="callback",
                  callback=dostuff,
                  metavar='LIST',
                  help='do stuff',
                  )

(options, args) = parser.parse_args()

:

Usage: opt.py [options]

Options:
  -h, --help            show this help message and exit
  -c LIST, --callback=LIST
                        do stuff
+2

metavar:

parser.add_option("-c", "--callback", dest="vararg_attr", action="callback", callback=vararg_callback, metavar='LIST')

: http://docs.python.org/library/optparse.html

+1

optparse does not display an indication for an optional argument if the type is None (default). If you specify the type and metavers, it is displayed in the help:

parser.add_option("-c", "--callback",
                  dest="vararg_attr",
                  type="string", 
                  metavar="LIST", 
                  action="callback", 
                  callback=vararg_callback,
                  help="do stuff")

Output:

Options:  
  -h, --help            show this help message and exit
  -c LIST, --callback=LIST
                        do stuff
0
source

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


All Articles