I am wrapping a class that exposes its OptionParser
through a property named options_parser
. I am wrapping this class in a 'runner' that I've written to use argparse. I use the ArgumentParser
's parse_known_args()
method to parse the wrapper's argument, and any of the remaining arguments I pass on to the instance of the wrapped class.
Running ./wrapper.py --help
does not list the options from the wrapped class. Is there a convenient way to add the optparse options to the wrapper's argparse argument?
If it's solely for displaying the options, one way I can think of is use the format_help
of optparse
and put it in the epilog of argparse
, for example:
In [303]: foo = OptionParser()
In [304]: foo.add_option("-f", "--file", dest="filename",help="read data from FILENAME")
In [305]: foo.add_option("-v", "--verbose",action="store_true", dest="verbose")
In [311]: bar = ArgumentParser(epilog = foo.format_help(), formatter_class = RawTextHelpFormatter)
In [312]: bar.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for the accumulator')
In [313]: bar.add_argument('--sum', dest='accumulate', action='store_const',const=sum, default=max,help='sum the integers (default: find the max)')
In [314]: bar.print_help()
usage: ipython [-h] [--sum] N [N ...]
positional arguments:
N an integer for the accumulator
optional arguments:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
Usage: ipython [options]
Options:
-h, --help show this help message and exit
-f FILENAME, --file=FILENAME
read data from FILENAME
-v, --verbose
You can of course format the epilog as you want, including some explanation about the two lists of options. You might also experiment with a different Formatter, though the default one doesn't work well in this case because it strips newlines from the epilog. If desperate about the layout you might also try to create your own formatter by subclassing argparse.HelpFormatter
, though I'd not recommend this based on class docs:
"""Formatter for generating usage messages and argument help strings.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""