pythoncallbackoptparse

Optparse: Usage on variable arg callback action does not indicate that extra params are needed


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

Adding the option like this:

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

The problem is, that there is no indication for the user that the option requires extra input:

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

Is there any way to change optparse's usage so that the usage will print something like:

-c=LIST, --callback=LIST

Solution

  • This involves monkeypatching and might not be the best solution. On the other hand, it seems to work.

    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()
    

    Output:

    Usage: opt.py [options]
    
    Options:
      -h, --help            show this help message and exit
      -c LIST, --callback=LIST
                            do stuff