By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,767 Members | 1,080 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,767 IT Pros & Developers. It's quick & easy.

Parsing complex options in Python

P: 92
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:

Expand|Select|Wrap|Line Numbers
  1. --basic_opt_1
  2. --basic_opt_2
  3. --basic_opt_3
  5. --super_opt_1 == basic_opt_1, basic_opt_3
  6. --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.OptionParser. Then after parsing do my validity checks. Then in my code I can do:

Expand|Select|Wrap|Line Numbers
  1. def option_1_is_set (options):
  2.     if options.basic_opt_1 or options.super_opt_2:
  3.         return True
  4.     return False
2. Use callbacks in the optparse.OptionParser for the super options. Here I would have the callback:

Expand|Select|Wrap|Line Numbers
  1. def super_opt_1_cb (option, opt_str, value, parser):
  2.     parser.values.basic_opt_1 = True
  3.     parser.values.basic_opt_2 = True
  5. def super_opt_2_cb (option, opt_str, value, parser):
  6.     parser.values.basic_opt_1 = True
  7.     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.
Jul 29 '08 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.