views:

390

answers:

2

I have 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 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

Thanks for your help!
Ben

+1  A: 

user the metavar keyword argument:

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

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

jcoon
Thanks, but I already tried this and it didn't work...
+1  A: 

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
Hao Lian
Thanks! This should work fine for me.