How can I flatten an optparse structure?

215 views Asked by At

I'm trying to build a management command for Django and I've run into an issue. It seems that the option_list variable needs to be a flattened list of options.

Here's the code — edited for brevity — that's executed:

def add_options(self, parser):
    group = OptionGroup(parser, "Global Options")
    group.add_option("--logfile", metavar="FILE", \
        help="log file. if omitted stderr will be used")
    ...
    ...
    ...
    group.add_option("-s", "--set", action="append", default=[], metavar="NAME=VALUE", \
        help="set/override setting (may be repeated)")
    parser.add_option_group(group)
    parser.add_option("-t", "--output-format", metavar="FORMAT", default="jsonlines", \
        help="format to use for dumping items with -o (default: %default)")

I need to take all the options parser variable, flatted then i.e. remove the OptionGroup, while keeping the options and put them into a new variable.

Django needs a class to specify it's options like this so it can iterate over it.

option_list = (
    make_option('-v', '--verbosity', action='store', dest='verbosity', default='1',
        type='choice', choices=['0', '1', '2', '3'],
        help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output'),
    make_option('--settings',
        help='The Python path to a settings module, e.g. "myproject.settings.main". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.'),
    make_option('--pythonpath',
        help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".'),
    make_option('--traceback', action='store_true',
        help='Print traceback on exception'),
)

I'm very lost with how to accomplish this.

2

There are 2 answers

0
AudioBubble On BEST ANSWER

You can get the option using the option_list attribute:

>>> print parser.option_list
[<Option at 0x7f938c8243f8: -h/--help>, <Option at 0x7f938c82b3f8: -t/--output-format>]

Unfortunately, that will miss out on the option group. For that, you will have to iterate over the groups in addition. Then, you can do something like (untested):

for group in parser.option_groups:
    option_list += tuple(group.option_list)
option_list += tuple(parser.option_list)

That will lose the grouping of options, but if you need that, you can probably fiddle around with things to get there.

In short, just use the option_list and option_groups attributes. How to find out yourself: use dir(parser) and look for the most applicable attributes; then it's a bit of trial and error.

0
Marwan Alsabbagh On

You should be able to just add the options like so:

option_list += (
    make_option("--logfile", metavar="FILE", \
        help="log file. if omitted stderr will be used"),
    make_option("-s", "--set", action="append", default=[], metavar="NAME=VALUE", \
        help="set/override setting (may be repeated)"),
)