1 from optparse
import Option
, OptionParser
, _match_abbrev
3 # This case-insensitive option parser relies on having a
4 # case-insensitive dictionary type available. Here's one
5 # for Python 2.2. Note that a *real* case-insensitive
6 # dictionary type would also have to implement __new__(),
7 # update(), and setdefault() -- but that's not the point
10 class caseless_dict (dict):
11 def __setitem__ (self
, key
, value
):
12 dict.__setitem
__(self
, key
.lower(), value
)
14 def __getitem__ (self
, key
):
15 return dict.__getitem
__(self
, key
.lower())
17 def get (self
, key
, default
=None):
18 return dict.get(self
, key
.lower())
20 def has_key (self
, key
):
21 return dict.has_key(self
, key
.lower())
24 class CaselessOptionParser (OptionParser
):
26 def _create_option_list (self
):
28 self
._short
_opt
= caseless_dict()
29 self
._long
_opt
= caseless_dict()
33 def _match_long_opt (self
, opt
):
34 return _match_abbrev(opt
.lower(), self
._long
_opt
.keys())
37 if __name__
== "__main__":
38 from optik
.errors
import OptionConflictError
40 # test 1: no options to start with
41 parser
= CaselessOptionParser()
43 parser
.add_option("-H", dest
="blah")
44 except OptionConflictError
:
45 print "ok: got OptionConflictError for -H"
47 print "not ok: no conflict between -h and -H"
49 parser
.add_option("-f", "--file", dest
="file")
50 #print repr(parser.get_option("-f"))
51 #print repr(parser.get_option("-F"))
52 #print repr(parser.get_option("--file"))
53 #print repr(parser.get_option("--fIlE"))
54 (options
, args
) = parser
.parse_args(["--FiLe", "foo"])
55 assert options
.file == "foo", options
.file
56 print "ok: case insensitive long options work"
58 (options
, args
) = parser
.parse_args(["-F", "bar"])
59 assert options
.file == "bar", options
.file
60 print "ok: case insensitive short options work"