Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame^] | 1 | import optparse |
| 2 | |
| 3 | class Option (optparse.Option): |
| 4 | ATTRS = optparse.Option.ATTRS + ['required'] |
| 5 | |
| 6 | def _check_required (self): |
| 7 | if self.required and not self.takes_value(): |
| 8 | raise OptionError( |
| 9 | "required flag set for option that doesn't take a value", |
| 10 | self) |
| 11 | |
| 12 | # Make sure _check_required() is called from the constructor! |
| 13 | CHECK_METHODS = optparse.Option.CHECK_METHODS + [_check_required] |
| 14 | |
| 15 | def process (self, opt, value, values, parser): |
| 16 | optparse.Option.process(self, opt, value, values, parser) |
| 17 | parser.option_seen[self] = 1 |
| 18 | |
| 19 | |
| 20 | class OptionParser (optparse.OptionParser): |
| 21 | |
| 22 | def _init_parsing_state (self): |
| 23 | optparse.OptionParser._init_parsing_state(self) |
| 24 | self.option_seen = {} |
| 25 | |
| 26 | def check_values (self, values, args): |
| 27 | for option in self.option_list: |
| 28 | if (isinstance(option, Option) and |
| 29 | option.required and |
| 30 | not self.option_seen.has_key(option)): |
| 31 | self.error("%s not supplied" % option) |
| 32 | return (values, args) |
| 33 | |
| 34 | |
| 35 | parser = OptionParser(option_list=[ |
| 36 | Option("-v", action="count", dest="verbose"), |
| 37 | Option("-f", "--file", required=1)]) |
| 38 | (options, args) = parser.parse_args() |
| 39 | |
| 40 | print "verbose:", options.verbose |
| 41 | print "file:", options.file |