1 """optparse - a powerful, extensible, and easy-to-use option parser.
2
3 By Greg Ward <gward@python.net>
4
5 Originally distributed as Optik; see http://optik.sourceforge.net/ .
6
7 If you have problems with this module, please do not file bugs,
8 patches, or feature requests with Python; instead, use Optik's
9 SourceForge project page:
10 http://sourceforge.net/projects/optik
11
12 For support, use the optik-users@lists.sourceforge.net mailing list
13 (http://lists.sourceforge.net/lists/listinfo/optik-users).
14 """
15
16
17
18
19 __version__ = "1.5.3"
20
21 __all__ = ['Option',
22 'SUPPRESS_HELP',
23 'SUPPRESS_USAGE',
24 'Values',
25 'OptionContainer',
26 'OptionGroup',
27 'OptionParser',
28 'HelpFormatter',
29 'IndentedHelpFormatter',
30 'TitledHelpFormatter',
31 'OptParseError',
32 'OptionError',
33 'OptionConflictError',
34 'OptionValueError',
35 'BadOptionError']
36
37 __copyright__ = """
38 Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
39 Copyright (c) 2002-2006 Python Software Foundation. All rights reserved.
40
41 Redistribution and use in source and binary forms, with or without
42 modification, are permitted provided that the following conditions are
43 met:
44
45 * Redistributions of source code must retain the above copyright
46 notice, this list of conditions and the following disclaimer.
47
48 * Redistributions in binary form must reproduce the above copyright
49 notice, this list of conditions and the following disclaimer in the
50 documentation and/or other materials provided with the distribution.
51
52 * Neither the name of the author nor the names of its
53 contributors may be used to endorse or promote products derived from
54 this software without specific prior written permission.
55
56 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
57 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
59 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
60 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
61 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
62 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
63 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
64 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
65 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
66 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
67 """
68
69 import string
70 import sys, os
71 import types
72 import textwrap
73
75 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
76
77
78 try:
79 sys.getdefaultencoding
80 except AttributeError:
83 sys.getdefaultencoding = fake_getdefaultencoding
84
85 try:
86 ''.encode
87 except AttributeError:
90 else:
92 return s.encode(encoding, replacement)
93
94
95
96
97
98
99
100
101 try:
102 from gettext import gettext
103 except ImportError:
104 - def gettext(message):
106 _ = gettext
107
108
115
116
118 """
119 Raised if an Option instance is created with invalid or
120 inconsistent arguments.
121 """
122
124 self.msg = msg
125 self.option_id = str(option)
126
128 if self.option_id:
129 return "option %s: %s" % (self.option_id, self.msg)
130 else:
131 return self.msg
132
134 """
135 Raised if conflicting options are added to an OptionParser.
136 """
137
139 """
140 Raised if an invalid option value is encountered on the command
141 line.
142 """
143
145 """
146 Raised if an invalid option is seen on the command line.
147 """
149 self.opt_str = opt_str
150
152 return _("no such option: %s") % self.opt_str
153
155 """
156 Raised if an ambiguous option is seen on the command line.
157 """
158 - def __init__(self, opt_str, possibilities):
161
163 return (_("ambiguous option: %s (%s?)")
164 % (self.opt_str, string.join(self.possibilities, ", ")))
165
166
374
392
393
411
412
414 if string.lower(val[:2]) == "0x":
415 radix = 16
416 elif string.lower(val[:2]) == "0b":
417 radix = 2
418 val = val[2:] or "0"
419 elif val[:1] == "0":
420 radix = 8
421 else:
422 radix = 10
423
424 return type(val, radix)
425
428
431
432 try:
433 int('0', 10)
434 except TypeError:
435
436 _parse_int = int
437
438 try:
439 long('0', 10)
440 except TypeError:
441
442 _parse_long = long
443
444 _builtin_cvt = { "int" : (_parse_int, _("integer")),
445 "long" : (_parse_long, _("long integer")),
446 "float" : (float, _("floating-point")),
447 "complex" : (complex, _("complex")) }
448
450 (cvt, what) = _builtin_cvt[option.type]
451 try:
452 return cvt(value)
453 except ValueError:
454 raise OptionValueError(
455 _("option %s: invalid %s value: %r") % (opt, what, value))
456
458 if value in option.choices:
459 return value
460 else:
461 choices = string.join(map(repr, option.choices), ", ")
462 raise OptionValueError(
463 _("option %s: invalid choice: %r (choose from %s)")
464 % (opt, value, choices))
465
466
467
468 NO_DEFAULT = ("NO", "DEFAULT")
469
470
472 """
473 Instance attributes:
474 _short_opts : [string]
475 _long_opts : [string]
476
477 action : string
478 type : string
479 dest : string
480 default : any
481 nargs : int
482 const : any
483 choices : [string]
484 callback : function
485 callback_args : (any*)
486 callback_kwargs : { string : any }
487 help : string
488 metavar : string
489 """
490
491
492
493 ATTRS = ['action',
494 'type',
495 'dest',
496 'default',
497 'nargs',
498 'const',
499 'choices',
500 'callback',
501 'callback_args',
502 'callback_kwargs',
503 'help',
504 'metavar']
505
506
507
508 ACTIONS = ("store",
509 "store_const",
510 "store_true",
511 "store_false",
512 "append",
513 "append_const",
514 "count",
515 "callback",
516 "help",
517 "version")
518
519
520
521
522 STORE_ACTIONS = ("store",
523 "store_const",
524 "store_true",
525 "store_false",
526 "append",
527 "append_const",
528 "count")
529
530
531
532 TYPED_ACTIONS = ("store",
533 "append",
534 "callback")
535
536
537
538 ALWAYS_TYPED_ACTIONS = ("store",
539 "append")
540
541
542 CONST_ACTIONS = ("store_const",
543 "append_const")
544
545
546
547 TYPES = ("string", "int", "long", "float", "complex", "choice")
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565 TYPE_CHECKER = { "int" : check_builtin,
566 "long" : check_builtin,
567 "float" : check_builtin,
568 "complex": check_builtin,
569 "choice" : check_choice,
570 }
571
572
573
574
575
576
577
578
579
580
581 CHECK_METHODS = None
582
583
584
585
604
606
607
608
609 opts = filter(None, opts)
610 if not opts:
611 raise TypeError("at least one option string must be supplied")
612 return opts
613
615 for opt in opts:
616 if len(opt) < 2:
617 raise OptionError(
618 "invalid option string %r: "
619 "must be at least two characters long" % opt, self)
620 elif len(opt) == 2:
621 if not (opt[0] == "-" and opt[1] != "-"):
622 raise OptionError(
623 "invalid short option string %r: "
624 "must be of the form -x, (x any non-dash char)" % opt,
625 self)
626 self._short_opts.append(opt)
627 else:
628 if not (opt[0:2] == "--" and opt[2] != "-"):
629 raise OptionError(
630 "invalid long option string %r: "
631 "must start with --, followed by non-dash" % opt,
632 self)
633 self._long_opts.append(opt)
634
636 for attr in self.ATTRS:
637 if attrs.has_key(attr):
638 setattr(self, attr, attrs[attr])
639 del attrs[attr]
640 else:
641 if attr == 'default':
642 setattr(self, attr, NO_DEFAULT)
643 else:
644 setattr(self, attr, None)
645 if attrs:
646 attrs = attrs.keys()
647 attrs.sort()
648 raise OptionError(
649 "invalid keyword arguments: %s" % string.join(attrs, ", "),
650 self)
651
652
653
654
656 if self.action is None:
657 self.action = "store"
658 elif self.action not in self.ACTIONS:
659 raise OptionError("invalid action: %r" % self.action, self)
660
662 if self.type is None:
663 if self.action in self.ALWAYS_TYPED_ACTIONS:
664 if self.choices is not None:
665
666 self.type = "choice"
667 else:
668
669 self.type = "string"
670 else:
671
672
673
674
675
676 import __builtin__
677 if ( type(self.type) is types.TypeType or
678 (hasattr(self.type, "__name__") and
679 getattr(__builtin__, self.type.__name__, None) is self.type) ):
680 self.type = self.type.__name__
681
682 if self.type == "str":
683 self.type = "string"
684
685 if self.type not in self.TYPES:
686 raise OptionError("invalid option type: %r" % self.type, self)
687 if self.action not in self.TYPED_ACTIONS:
688 raise OptionError(
689 "must not supply a type for action %r" % self.action, self)
690
692 if self.type == "choice":
693 if self.choices is None:
694 raise OptionError(
695 "must supply a list of choices for type 'choice'", self)
696 elif type(self.choices) not in (types.TupleType, types.ListType):
697 raise OptionError(
698 "choices must be a list of strings ('%s' supplied)"
699 % string.split(str(type(self.choices)), "'")[1], self)
700 elif self.choices is not None:
701 raise OptionError(
702 "must not supply choices for type %r" % self.type, self)
703
705
706
707 takes_value = (self.action in self.STORE_ACTIONS or
708 self.type is not None)
709 if self.dest is None and takes_value:
710
711
712
713 if self._long_opts:
714
715 self.dest = string.replace(self._long_opts[0][2:], '-', '_')
716 else:
717 self.dest = self._short_opts[0][1]
718
720 if self.action not in self.CONST_ACTIONS and self.const is not None:
721 raise OptionError(
722 "'const' must not be supplied for action %r" % self.action,
723 self)
724
726 if self.action in self.TYPED_ACTIONS:
727 if self.nargs is None:
728 self.nargs = 1
729 elif self.nargs is not None:
730 raise OptionError(
731 "'nargs' must not be supplied for action %r" % self.action,
732 self)
733
735 if self.action == "callback":
736 if not callable(self.callback):
737 raise OptionError(
738 "callback not callable: %r" % self.callback, self)
739 if (self.callback_args is not None and
740 type(self.callback_args) is not types.TupleType):
741 raise OptionError(
742 "callback_args, if supplied, must be a tuple: not %r"
743 % self.callback_args, self)
744 if (self.callback_kwargs is not None and
745 type(self.callback_kwargs) is not types.DictType):
746 raise OptionError(
747 "callback_kwargs, if supplied, must be a dict: not %r"
748 % self.callback_kwargs, self)
749 else:
750 if self.callback is not None:
751 raise OptionError(
752 "callback supplied (%r) for non-callback option"
753 % self.callback, self)
754 if self.callback_args is not None:
755 raise OptionError(
756 "callback_args supplied for non-callback option", self)
757 if self.callback_kwargs is not None:
758 raise OptionError(
759 "callback_kwargs supplied for non-callback option", self)
760
761
762 CHECK_METHODS = [_check_action,
763 _check_type,
764 _check_choice,
765 _check_dest,
766 _check_const,
767 _check_nargs,
768 _check_callback]
769
770
771
772
774 return string.join(self._short_opts + self._long_opts, "/")
775
776 __repr__ = _repr
777
779 return self.type is not None
780
782 if self._long_opts:
783 return self._long_opts[0]
784 else:
785 return self._short_opts[0]
786
787
788
789
791 checker = self.TYPE_CHECKER.get(self.type)
792 if checker is None:
793 return value
794 else:
795 return checker(self, opt, value)
796
798 if value is not None:
799 if self.nargs == 1:
800 return self.check_value(opt, value)
801 else:
802 return tuple(map(lambda v, o=opt, s=self: s.check_value(o, v), value))
803
804 - def process(self, opt, value, values, parser):
805
806
807
808 value = self.convert_value(opt, value)
809
810
811
812
813 return self.take_action(
814 self.action, self.dest, opt, value, values, parser)
815
816 - def take_action(self, action, dest, opt, value, values, parser):
817 if action == "store":
818 setattr(values, dest, value)
819 elif action == "store_const":
820 setattr(values, dest, self.const)
821 elif action == "store_true":
822 setattr(values, dest, True)
823 elif action == "store_false":
824 setattr(values, dest, False)
825 elif action == "append":
826 values.ensure_value(dest, []).append(value)
827 elif action == "append_const":
828 values.ensure_value(dest, []).append(self.const)
829 elif action == "count":
830 setattr(values, dest, values.ensure_value(dest, 0) + 1)
831 elif action == "callback":
832 args = self.callback_args or ()
833 kwargs = self.callback_kwargs or {}
834 apply(self.callback, (self, opt, value, parser,) + args, kwargs)
835 elif action == "help":
836 parser.print_help()
837 parser.exit()
838 elif action == "version":
839 parser.print_version()
840 parser.exit()
841 else:
842 raise RuntimeError, "unknown action %r" % self.action
843
844 return 1
845
846
847
848
849 SUPPRESS_HELP = "SUPPRESS"+"HELP"
850 SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
851
852
853 try:
854 True, False
855 except NameError:
856 (True, False) = (1, 0)
857
858 try:
859 types.UnicodeType
860 except AttributeError:
862 return isinstance(x, types.StringType)
863 else:
865 return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType)
866
868
870 if defaults:
871 for (attr, val) in defaults.items():
872 setattr(self, attr, val)
873
875 return str(self.__dict__)
876
877 __repr__ = _repr
878
880 if isinstance(other, Values):
881 return cmp(self.__dict__, other.__dict__)
882 elif isinstance(other, types.DictType):
883 return cmp(self.__dict__, other)
884 else:
885 return -1
886
888 """
889 Update the option values from an arbitrary dictionary, but only
890 use keys from dict that already have a corresponding attribute
891 in self. Any keys in dict without a corresponding attribute
892 are silently ignored.
893 """
894 for attr in dir(self):
895 if dict.has_key(attr):
896 dval = dict[attr]
897 if dval is not None:
898 setattr(self, attr, dval)
899
901 """
902 Update the option values from an arbitrary dictionary,
903 using all keys from the dictionary regardless of whether
904 they have a corresponding attribute in self or not.
905 """
906 self.__dict__.update(dict)
907
915
917 __import__(modname)
918 mod = sys.modules[modname]
919 self._update(vars(mod), mode)
920
921 - def read_file(self, filename, mode="careful"):
922 vars = {}
923 exec open(filename, 'rU').read() in vars
924 self._update(vars, mode)
925
927 if not hasattr(self, attr) or getattr(self, attr) is None:
928 setattr(self, attr, value)
929 return getattr(self, attr)
930
931
933
934 """
935 Abstract base class.
936
937 Class attributes:
938 standard_option_list : [Option]
939 list of standard options that will be accepted by all instances
940 of this parser class (intended to be overridden by subclasses).
941
942 Instance attributes:
943 option_list : [Option]
944 the list of Option objects contained by this OptionContainer
945 _short_opt : { string : Option }
946 dictionary mapping short option strings, eg. "-f" or "-X",
947 to the Option instances that implement them. If an Option
948 has multiple short option strings, it will appears in this
949 dictionary multiple times. [1]
950 _long_opt : { string : Option }
951 dictionary mapping long option strings, eg. "--file" or
952 "--exclude", to the Option instances that implement them.
953 Again, a given Option can occur multiple times in this
954 dictionary. [1]
955 defaults : { string : any }
956 dictionary mapping option destination names to default
957 values for each destination [1]
958
959 [1] These mappings are common to (shared by) all components of the
960 controlling OptionParser, where they are initially created.
961
962 """
963
964 - def __init__(self, option_class, conflict_handler, description):
974
976
977
978
979 self._short_opt = {}
980 self._long_opt = {}
981 self.defaults = {}
982
983
985
986
987 self._short_opt = parser._short_opt
988 self._long_opt = parser._long_opt
989 self.defaults = parser.defaults
990
992 if handler not in ("error", "resolve"):
993 raise ValueError, "invalid conflict_resolution value %r" % handler
994 self.conflict_handler = handler
995
997 self.description = description
998
1000 return self.description
1001
1002
1004 """see OptionParser.destroy()."""
1005 del self._short_opt
1006 del self._long_opt
1007 del self.defaults
1008
1009
1010
1011
1013 conflict_opts = []
1014 for opt in option._short_opts:
1015 if self._short_opt.has_key(opt):
1016 conflict_opts.append((opt, self._short_opt[opt]))
1017 for opt in option._long_opts:
1018 if self._long_opt.has_key(opt):
1019 conflict_opts.append((opt, self._long_opt[opt]))
1020
1021 if conflict_opts:
1022 handler = self.conflict_handler
1023 if handler == "error":
1024 raise OptionConflictError(
1025 "conflicting option string(s): %s"
1026 % string.join(map(lambda co: co[0], conflict_opts), ", "),
1027 option)
1028 elif handler == "resolve":
1029 for (opt, c_option) in conflict_opts:
1030 if opt[:2] == "--":
1031 c_option._long_opts.remove(opt)
1032 del self._long_opt[opt]
1033 else:
1034 c_option._short_opts.remove(opt)
1035 del self._short_opt[opt]
1036 if not (c_option._short_opts or c_option._long_opts):
1037 c_option.container.option_list.remove(c_option)
1038
1040 """add_option(Option)
1041 add_option(opt_str, ..., kwarg=val, ...)
1042 """
1043 if type(args[0]) is types.StringType:
1044 option = apply(self.option_class, args, kwargs)
1045 elif len(args) == 1 and not kwargs:
1046 option = args[0]
1047 if not isinstance(option, Option):
1048 raise TypeError, "not an Option instance: %r" % option
1049 else:
1050 raise TypeError, "invalid arguments"
1051
1052 self._check_conflict(option)
1053
1054 self.option_list.append(option)
1055 option.container = self
1056 for opt in option._short_opts:
1057 self._short_opt[opt] = option
1058 for opt in option._long_opts:
1059 self._long_opt[opt] = option
1060
1061 if option.dest is not None:
1062 if option.default is not NO_DEFAULT:
1063 self.defaults[option.dest] = option.default
1064 elif not self.defaults.has_key(option.dest):
1065 self.defaults[option.dest] = None
1066
1067 return option
1068
1070 for option in option_list:
1071 self.add_option(option)
1072
1073
1074
1076 return (self._short_opt.get(opt_str) or
1077 self._long_opt.get(opt_str))
1078
1080 return (self._short_opt.has_key(opt_str) or
1081 self._long_opt.has_key(opt_str))
1082
1084 option = self._short_opt.get(opt_str)
1085 if option is None:
1086 option = self._long_opt.get(opt_str)
1087 if option is None:
1088 raise ValueError("no such option %r" % opt_str)
1089
1090 for opt in option._short_opts:
1091 del self._short_opt[opt]
1092 for opt in option._long_opts:
1093 del self._long_opt[opt]
1094 option.container.option_list.remove(option)
1095
1096
1097
1098
1107
1110
1118
1119
1121
1122 - def __init__(self, parser, title, description=None):
1123 self.parser = parser
1124 OptionContainer.__init__(
1125 self, parser.option_class, parser.conflict_handler, description)
1126 self.title = title
1127
1131
1134
1139
1140
1141
1148
1149
1151
1152 """
1153 Class attributes:
1154 standard_option_list : [Option]
1155 list of standard options that will be accepted by all instances
1156 of this parser class (intended to be overridden by subclasses).
1157
1158 Instance attributes:
1159 usage : string
1160 a usage string for your program. Before it is displayed
1161 to the user, "%prog" will be expanded to the name of
1162 your program (self.prog or os.path.basename(sys.argv[0])).
1163 prog : string
1164 the name of the current program (to override
1165 os.path.basename(sys.argv[0])).
1166 epilog : string
1167 paragraph of help text to print after option help
1168
1169 option_groups : [OptionGroup]
1170 list of option groups in this parser (option groups are
1171 irrelevant for parsing the command-line, but very useful
1172 for generating help)
1173
1174 allow_interspersed_args : bool = true
1175 if true, positional arguments may be interspersed with options.
1176 Assuming -a and -b each take a single argument, the command-line
1177 -ablah foo bar -bboo baz
1178 will be interpreted the same as
1179 -ablah -bboo -- foo bar baz
1180 If this flag were false, that command line would be interpreted as
1181 -ablah -- foo bar -bboo baz
1182 -- ie. we stop processing options as soon as we see the first
1183 non-option argument. (This is the tradition followed by
1184 Python's getopt module, Perl's Getopt::Std, and other argument-
1185 parsing libraries, but it is generally annoying to users.)
1186
1187 process_default_values : bool = true
1188 if true, option default values are processed similarly to option
1189 values from the command line: that is, they are passed to the
1190 type-checking function for the option's type (as long as the
1191 default value is a string). (This really only matters if you
1192 have defined custom types; see SF bug #955889.) Set it to false
1193 to restore the behaviour of Optik 1.4.1 and earlier.
1194
1195 rargs : [string]
1196 the argument list currently being parsed. Only set when
1197 parse_args() is active, and continually trimmed down as
1198 we consume arguments. Mainly there for the benefit of
1199 callback options.
1200 largs : [string]
1201 the list of leftover arguments that we have skipped while
1202 parsing options. If allow_interspersed_args is false, this
1203 list is always empty.
1204 values : Values
1205 the set of option values currently being accumulated. Only
1206 set when parse_args() is active. Also mainly for callbacks.
1207
1208 Because of the 'rargs', 'largs', and 'values' attributes,
1209 OptionParser is not thread-safe. If, for some perverse reason, you
1210 need to parse command-line arguments simultaneously in different
1211 threads, use different OptionParser instances.
1212
1213 """
1214
1215 standard_option_list = []
1216
1217 - def __init__(self,
1218 usage=None,
1219 option_list=None,
1220 option_class=Option,
1221 version=None,
1222 conflict_handler="error",
1223 description=None,
1224 formatter=None,
1225 add_help_option=True,
1226 prog=None,
1227 epilog=None):
1249
1250
1252 """
1253 Declare that you are done with this OptionParser. This cleans up
1254 reference cycles so the OptionParser (and all objects referenced by
1255 it) can be garbage-collected promptly. After calling destroy(), the
1256 OptionParser is unusable.
1257 """
1258 OptionContainer.destroy(self)
1259 for group in self.option_groups:
1260 group.destroy()
1261 del self.option_list
1262 del self.option_groups
1263 del self.formatter
1264
1265
1266
1267
1268
1273
1275 self.add_option("-h", "--help",
1276 action="help",
1277 help=_("show this help message and exit"))
1278
1280 self.add_option("--version",
1281 action="version",
1282 help=_("show program's version number and exit"))
1283
1293
1295
1296 self.rargs = None
1297 self.largs = None
1298 self.values = None
1299
1300
1301
1302
1304 if usage is None:
1305 self.usage = _("%prog [options]")
1306 elif usage is SUPPRESS_USAGE:
1307 self.usage = None
1308
1309 elif string.lower(usage)[:7] == "usage: ":
1310 self.usage = usage[7:]
1311 else:
1312 self.usage = usage
1313
1315 self.allow_interspersed_args = True
1316
1318 self.allow_interspersed_args = False
1319
1321 self.process_default_values = process
1322
1324 self.defaults[dest] = value
1325
1327 self.defaults.update(kwargs)
1328
1330 options = self.option_list[:]
1331 for group in self.option_groups:
1332 options.extend(group.option_list)
1333 return options
1334
1348
1349
1350
1351
1353
1354 if type(args[0]) is types.StringType:
1355 group = apply(OptionGroup, (self,) + args, kwargs)
1356 elif len(args) == 1 and not kwargs:
1357 group = args[0]
1358 if not isinstance(group, OptionGroup):
1359 raise TypeError, "not an OptionGroup instance: %r" % group
1360 if group.parser is not self:
1361 raise ValueError, "invalid OptionGroup (wrong parser)"
1362 else:
1363 raise TypeError, "invalid arguments"
1364
1365 self.option_groups.append(group)
1366 return group
1367
1369 option = (self._short_opt.get(opt_str) or
1370 self._long_opt.get(opt_str))
1371 if option and option.container is not self:
1372 return option.container
1373 return None
1374
1375
1376
1377
1379 if args is None:
1380 return sys.argv[1:]
1381 else:
1382 return args[:]
1383
1385 """
1386 parse_args(args : [string] = sys.argv[1:],
1387 values : Values = None)
1388 -> (values : Values, args : [string])
1389
1390 Parse the command-line options found in 'args' (default:
1391 sys.argv[1:]). Any errors result in a call to 'error()', which
1392 by default prints the usage message to stderr and calls
1393 sys.exit() with an error message. On success returns a pair
1394 (values, args) where 'values' is an Values instance (with all
1395 your option values) and 'args' is the list of arguments left
1396 over after parsing options.
1397 """
1398 rargs = self._get_args(args)
1399 if values is None:
1400 values = self.get_default_values()
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411 self.rargs = rargs
1412 self.largs = largs = []
1413 self.values = values
1414
1415 try:
1416 stop = self._process_args(largs, rargs, values)
1417 except (BadOptionError, OptionValueError), err:
1418 self.error(str(err))
1419
1420 args = largs + rargs
1421 return self.check_values(values, args)
1422
1424 """
1425 check_values(values : Values, args : [string])
1426 -> (values : Values, args : [string])
1427
1428 Check that the supplied option values and leftover arguments are
1429 valid. Returns the option values and leftover arguments
1430 (possibly adjusted, possibly completely new -- whatever you
1431 like). Default implementation just returns the passed-in
1432 values; subclasses may override as desired.
1433 """
1434 return (values, args)
1435
1437 """_process_args(largs : [string],
1438 rargs : [string],
1439 values : Values)
1440
1441 Process command-line arguments and populate 'values', consuming
1442 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1443 false, stop at the first non-option argument. If true, accumulate any
1444 interspersed non-option arguments in 'largs'.
1445 """
1446 while rargs:
1447 arg = rargs[0]
1448
1449
1450
1451 if arg == "--":
1452 del rargs[0]
1453 return
1454 elif arg[0:2] == "--":
1455
1456 self._process_long_opt(rargs, values)
1457 elif arg[:1] == "-" and len(arg) > 1:
1458
1459
1460 self._process_short_opts(rargs, values)
1461 elif self.allow_interspersed_args:
1462 largs.append(arg)
1463 del rargs[0]
1464 else:
1465 return
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1488 """_match_long_opt(opt : string) -> string
1489
1490 Determine which long option string 'opt' matches, ie. which one
1491 it is an unambiguous abbrevation for. Raises BadOptionError if
1492 'opt' doesn't unambiguously match any long option string.
1493 """
1494 return _match_abbrev(opt, self._long_opt)
1495
1497 arg = rargs.pop(0)
1498
1499
1500
1501 if "=" in arg:
1502 (opt, next_arg) = string.split(arg, "=", 1)
1503 rargs.insert(0, next_arg)
1504 had_explicit_value = True
1505 else:
1506 opt = arg
1507 had_explicit_value = False
1508
1509 opt = self._match_long_opt(opt)
1510 option = self._long_opt[opt]
1511 if option.takes_value():
1512 nargs = option.nargs
1513 if len(rargs) < nargs:
1514 if nargs == 1:
1515 self.error(_("%s option requires an argument") % opt)
1516 else:
1517 self.error(_("%s option requires %d arguments")
1518 % (opt, nargs))
1519 elif nargs == 1:
1520 value = rargs.pop(0)
1521 else:
1522 value = tuple(rargs[0:nargs])
1523 del rargs[0:nargs]
1524
1525 elif had_explicit_value:
1526 self.error(_("%s option does not take a value") % opt)
1527
1528 else:
1529 value = None
1530
1531 option.process(opt, value, values, self)
1532
1534 arg = rargs.pop(0)
1535 stop = False
1536 i = 1
1537 for ch in arg[1:]:
1538 opt = "-" + ch
1539 option = self._short_opt.get(opt)
1540 i = i + 1
1541
1542 if not option:
1543 raise BadOptionError(opt)
1544 if option.takes_value():
1545
1546
1547 if i < len(arg):
1548 rargs.insert(0, arg[i:])
1549 stop = True
1550
1551 nargs = option.nargs
1552 if len(rargs) < nargs:
1553 if nargs == 1:
1554 self.error(_("%s option requires an argument") % opt)
1555 else:
1556 self.error(_("%s option requires %d arguments")
1557 % (opt, nargs))
1558 elif nargs == 1:
1559 value = rargs.pop(0)
1560 else:
1561 value = tuple(rargs[0:nargs])
1562 del rargs[0:nargs]
1563
1564 else:
1565 value = None
1566
1567 option.process(opt, value, values, self)
1568
1569 if stop:
1570 break
1571
1572
1573
1574
1576 if self.prog is None:
1577 return os.path.basename(sys.argv[0])
1578 else:
1579 return self.prog
1580
1583
1586
1587 - def exit(self, status=0, msg=None):
1591
1593 """error(msg : string)
1594
1595 Print a usage message incorporating 'msg' to stderr and exit.
1596 If you override this in a subclass, it should not return -- it
1597 should either exit or raise an exception.
1598 """
1599 self.print_usage(sys.stderr)
1600 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
1601
1608
1610 """print_usage(file : file = stdout)
1611
1612 Print the usage message for the current program (self.usage) to
1613 'file' (default stdout). Any occurence of the string "%prog" in
1614 self.usage is replaced with the name of the current program
1615 (basename of sys.argv[0]). Does nothing if self.usage is empty
1616 or not defined.
1617 """
1618 if self.usage:
1619 file.write(self.get_usage() + '\n')
1620
1622 if self.version:
1623 return self.expand_prog_name(self.version)
1624 else:
1625 return ""
1626
1628 """print_version(file : file = stdout)
1629
1630 Print the version message for this program (self.version) to
1631 'file' (default stdout). As with print_usage(), any occurence
1632 of "%prog" in self.version is replaced by the current program's
1633 name. Does nothing if self.version is empty or undefined.
1634 """
1635 if self.version:
1636 file.write(self.get_version() + '\n')
1637
1654
1657
1669
1670
1672 encoding = getattr(file, "encoding", None)
1673 if not encoding:
1674 encoding = sys.getdefaultencoding()
1675 return encoding
1676
1678 """print_help(file : file = stdout)
1679
1680 Print an extended help message, listing all options and any
1681 help text provided with them, to 'file' (default stdout).
1682 """
1683 if file is None:
1684 file = sys.stdout
1685 encoding = self._get_encoding(file)
1686 file.write(encode_wrapper(self.format_help(), encoding, "replace"))
1687
1688
1689
1690
1692 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1693
1694 Return the string key in 'wordmap' for which 's' is an unambiguous
1695 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1696 'words', raise BadOptionError.
1697 """
1698
1699 if wordmap.has_key(s):
1700 return s
1701 else:
1702
1703 possibilities = filter(lambda w, s=s: w[:len(s)] == s, wordmap.keys())
1704
1705 if len(possibilities) == 1:
1706 return possibilities[0]
1707 elif not possibilities:
1708 raise BadOptionError(s)
1709 else:
1710
1711 possibilities.sort()
1712 raise AmbiguousOptionError(s, possibilities)
1713
1714
1715
1716
1717
1718
1719 make_option = Option
1720
1721
1722
1723
1724
1725
1726