Parsing complex options in Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Benny the Guard
    New Member
    • Jun 2007
    • 92

    Parsing complex options in Python

    I have become familiar with optparse code to parse various options into a program. But right now having some difficulties with a new project I am working on (not a class project, just a new script).

    What I need is a command line util that can take various flags, these are 100% inclusive with no overlap. Easy, but now I want to also create some super-flags that setup a bunch of different values, and are exclusive to other super-flags. So for example i might have:

    Code:
    --basic_opt_1
    --basic_opt_2
    --basic_opt_3
    
    --super_opt_1 == basic_opt_1, basic_opt_3
    --super_opt_2 == basic_opt_1, basic_opt_2
    Now I need an option parser that sets up the values correctly and ensures only one or none of the super options is used. My brainstorming led to the following possabilities:

    1. Create the super tags as regular options in optparse.Option Parser. Then after parsing do my validity checks. Then in my code I can do:

    Code:
    def option_1_is_set (options):
        if options.basic_opt_1 or options.super_opt_2:
            return True
        return False
    2. Use callbacks in the optparse.Option Parser for the super options. Here I would have the callback:

    Code:
    def super_opt_1_cb (option, opt_str, value, parser):
        parser.values.basic_opt_1 = True
        parser.values.basic_opt_2 = True
    
    def super_opt_2_cb (option, opt_str, value, parser):
        parser.values.basic_opt_1 = True
        parser.values.basic_opt_3 = True
    But this will be more difficult to error check.

    3. Roll my own parser where I check for options on my own, first looking up the super ones to configure the defaults, then looking for any additional basic ones. If I could configure OptionParser to not exit on unknown flags I could do a two pass here, first one sets up the default values for the second on based on the super flags (if any) and then the second one is normal..... but that requires hacking the optparse code.
Working...