Search code examples
pythonargparseoptparse

How do I get optparse list all possible arguments and options?


I'm using Python 2.6.2 (unfortunately can't upgrade to 2.7, or I'd use argparse). How can I get optparse to return a list of the options that have been added via 'add_option'?

Here's some sample code:

from optparse import OptionParser
parser = OptionParser()
parser.add_option('--one')
parser.add_option('--two')
(opts,args) = parser.parser_args()

optlist = parser.funcToGetListOfOptions()
print optlist
['one', 'two']

I've looked through the optparse source and can figure it out by accessing internal attributes, but that doesn't seem very kosher. What's the right way to do this?

Thanks!


Solution

  • >>> parser._get_all_options()[1:]
    [<Option at 0xb7d185ec: --one>, <Option at 0xb7d1866c: --two>]
    >>> [x.get_opt_string() for x in parser._get_all_options()[1:]]
    ['--one', '--two']
    >>> [x.dest for x in parser._get_all_options()[1:]]
    ['one', 'two']