1 | # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) |
---|
2 | # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php |
---|
3 | """ |
---|
4 | A subclass of ``optparse.OptionParser`` that allows boolean long |
---|
5 | options (like ``--verbose``) to also take arguments (like |
---|
6 | ``--verbose=true``). Arguments *must* use ``=``. |
---|
7 | """ |
---|
8 | |
---|
9 | import optparse |
---|
10 | try: |
---|
11 | _ = optparse._ |
---|
12 | except AttributeError: |
---|
13 | from gettext import gettext as _ |
---|
14 | |
---|
15 | class BoolOptionParser(optparse.OptionParser): |
---|
16 | |
---|
17 | def _process_long_opt(self, rargs, values): |
---|
18 | arg = rargs.pop(0) |
---|
19 | |
---|
20 | # Value explicitly attached to arg? Pretend it's the next |
---|
21 | # argument. |
---|
22 | if "=" in arg: |
---|
23 | (opt, next_arg) = arg.split("=", 1) |
---|
24 | rargs.insert(0, next_arg) |
---|
25 | had_explicit_value = True |
---|
26 | else: |
---|
27 | opt = arg |
---|
28 | had_explicit_value = False |
---|
29 | |
---|
30 | opt = self._match_long_opt(opt) |
---|
31 | option = self._long_opt[opt] |
---|
32 | if option.takes_value(): |
---|
33 | nargs = option.nargs |
---|
34 | if len(rargs) < nargs: |
---|
35 | if nargs == 1: |
---|
36 | self.error(_("%s option requires an argument") % opt) |
---|
37 | else: |
---|
38 | self.error(_("%s option requires %d arguments") |
---|
39 | % (opt, nargs)) |
---|
40 | elif nargs == 1: |
---|
41 | value = rargs.pop(0) |
---|
42 | else: |
---|
43 | value = tuple(rargs[0:nargs]) |
---|
44 | del rargs[0:nargs] |
---|
45 | |
---|
46 | elif had_explicit_value: |
---|
47 | value = rargs[0].lower().strip() |
---|
48 | del rargs[0:1] |
---|
49 | if value in ('true', 'yes', 'on', '1', 'y', 't'): |
---|
50 | value = None |
---|
51 | elif value in ('false', 'no', 'off', '0', 'n', 'f'): |
---|
52 | # Don't process |
---|
53 | return |
---|
54 | else: |
---|
55 | self.error(_('%s option takes a boolean value only (true/false)') % opt) |
---|
56 | |
---|
57 | else: |
---|
58 | value = None |
---|
59 | |
---|
60 | option.process(opt, value, values, self) |
---|