##// END OF EJS Templates
Update argparse to current SVN....
Fernando Perez -
Show More
@@ -1,2278 +1,2323 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright © 2006-2009 Steven J. Bethard <steven.bethard@gmail.com>.
3 # Copyright © 2006-2009 Steven J. Bethard <steven.bethard@gmail.com>.
4 #
4 #
5 # Redistribution and use in source and binary forms, with or without
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may not
6 # modification, are permitted provided that the following conditions are met:
6 # use this file except in compliance with the License. You may obtain a copy
7 # of the License at
7 #
8 #
8 # * Redistributions of source code must retain the above copyright notice, this
9 # http://www.apache.org/licenses/LICENSE-2.0
9 # list of conditions and the following disclaimer.
10 # * Redistributions in binary form must reproduce the above copyright notice,
11 # this list of conditions and the following disclaimer in the documentation
12 # and/or other materials provided with the distribution.
13 #
10 #
14 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
11 # Unless required by applicable law or agreed to in writing, software
15 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
14 # License for the specific language governing permissions and limitations
18 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
15 # under the License.
19 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20 # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22 # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24
16
25 """Command-line parsing library
17 """Command-line parsing library
26
18
27 This module is an optparse-inspired command-line parsing library that:
19 This module is an optparse-inspired command-line parsing library that:
28
20
29 - handles both optional and positional arguments
21 - handles both optional and positional arguments
30 - produces highly informative usage messages
22 - produces highly informative usage messages
31 - supports parsers that dispatch to sub-parsers
23 - supports parsers that dispatch to sub-parsers
32
24
33 The following is a simple usage example that sums integers from the
25 The following is a simple usage example that sums integers from the
34 command-line and writes the result to a file::
26 command-line and writes the result to a file::
35
27
36 parser = argparse.ArgumentParser(
28 parser = argparse.ArgumentParser(
37 description='sum the integers at the command line')
29 description='sum the integers at the command line')
38 parser.add_argument(
30 parser.add_argument(
39 'integers', metavar='int', nargs='+', type=int,
31 'integers', metavar='int', nargs='+', type=int,
40 help='an integer to be summed')
32 help='an integer to be summed')
41 parser.add_argument(
33 parser.add_argument(
42 '--log', default=sys.stdout, type=argparse.FileType('w'),
34 '--log', default=sys.stdout, type=argparse.FileType('w'),
43 help='the file where the sum should be written')
35 help='the file where the sum should be written')
44 args = parser.parse_args()
36 args = parser.parse_args()
45 args.log.write('%s' % sum(args.integers))
37 args.log.write('%s' % sum(args.integers))
46 args.log.close()
38 args.log.close()
47
39
48 The module contains the following public classes:
40 The module contains the following public classes:
49
41
50 - ArgumentParser -- The main entry point for command-line parsing. As the
42 - ArgumentParser -- The main entry point for command-line parsing. As the
51 example above shows, the add_argument() method is used to populate
43 example above shows, the add_argument() method is used to populate
52 the parser with actions for optional and positional arguments. Then
44 the parser with actions for optional and positional arguments. Then
53 the parse_args() method is invoked to convert the args at the
45 the parse_args() method is invoked to convert the args at the
54 command-line into an object with attributes.
46 command-line into an object with attributes.
55
47
56 - ArgumentError -- The exception raised by ArgumentParser objects when
48 - ArgumentError -- The exception raised by ArgumentParser objects when
57 there are errors with the parser's actions. Errors raised while
49 there are errors with the parser's actions. Errors raised while
58 parsing the command-line are caught by ArgumentParser and emitted
50 parsing the command-line are caught by ArgumentParser and emitted
59 as command-line messages.
51 as command-line messages.
60
52
61 - FileType -- A factory for defining types of files to be created. As the
53 - FileType -- A factory for defining types of files to be created. As the
62 example above shows, instances of FileType are typically passed as
54 example above shows, instances of FileType are typically passed as
63 the type= argument of add_argument() calls.
55 the type= argument of add_argument() calls.
64
56
65 - Action -- The base class for parser actions. Typically actions are
57 - Action -- The base class for parser actions. Typically actions are
66 selected by passing strings like 'store_true' or 'append_const' to
58 selected by passing strings like 'store_true' or 'append_const' to
67 the action= argument of add_argument(). However, for greater
59 the action= argument of add_argument(). However, for greater
68 customization of ArgumentParser actions, subclasses of Action may
60 customization of ArgumentParser actions, subclasses of Action may
69 be defined and passed as the action= argument.
61 be defined and passed as the action= argument.
70
62
71 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
63 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
72 ArgumentDefaultsHelpFormatter -- Formatter classes which
64 ArgumentDefaultsHelpFormatter -- Formatter classes which
73 may be passed as the formatter_class= argument to the
65 may be passed as the formatter_class= argument to the
74 ArgumentParser constructor. HelpFormatter is the default,
66 ArgumentParser constructor. HelpFormatter is the default,
75 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
67 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
76 not to change the formatting for help text, and
68 not to change the formatting for help text, and
77 ArgumentDefaultsHelpFormatter adds information about argument defaults
69 ArgumentDefaultsHelpFormatter adds information about argument defaults
78 to the help.
70 to the help.
79
71
80 All other classes in this module are considered implementation details.
72 All other classes in this module are considered implementation details.
81 (Also note that HelpFormatter and RawDescriptionHelpFormatter are only
73 (Also note that HelpFormatter and RawDescriptionHelpFormatter are only
82 considered public as object names -- the API of the formatter objects is
74 considered public as object names -- the API of the formatter objects is
83 still considered an implementation detail.)
75 still considered an implementation detail.)
84 """
76 """
85
77
86 __version__ = '1.0.1'
78 __version__ = '1.1a1'
87 __all__ = [
79 __all__ = [
88 'ArgumentParser',
80 'ArgumentParser',
89 'ArgumentError',
81 'ArgumentError',
90 'Namespace',
82 'Namespace',
91 'Action',
83 'Action',
92 'FileType',
84 'FileType',
93 'HelpFormatter',
85 'HelpFormatter',
94 'RawDescriptionHelpFormatter',
86 'RawDescriptionHelpFormatter',
95 'RawTextHelpFormatter'
87 'RawTextHelpFormatter',
96 'ArgumentDefaultsHelpFormatter',
88 'ArgumentDefaultsHelpFormatter',
97 ]
89 ]
98
90
99
91
100 import copy as _copy
92 import copy as _copy
101 import os as _os
93 import os as _os
102 import re as _re
94 import re as _re
103 import sys as _sys
95 import sys as _sys
104 import textwrap as _textwrap
96 import textwrap as _textwrap
105
97
106 from gettext import gettext as _
98 from gettext import gettext as _
107
99
108 try:
100 try:
109 _set = set
101 _set = set
110 except NameError:
102 except NameError:
111 from sets import Set as _set
103 from sets import Set as _set
112
104
113 try:
105 try:
114 _basestring = basestring
106 _basestring = basestring
115 except NameError:
107 except NameError:
116 _basestring = str
108 _basestring = str
117
109
118 try:
110 try:
119 _sorted = sorted
111 _sorted = sorted
120 except NameError:
112 except NameError:
121
113
122 def _sorted(iterable, reverse=False):
114 def _sorted(iterable, reverse=False):
123 result = list(iterable)
115 result = list(iterable)
124 result.sort()
116 result.sort()
125 if reverse:
117 if reverse:
126 result.reverse()
118 result.reverse()
127 return result
119 return result
128
120
121
122 def _callable(obj):
123 return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
124
129 # silence Python 2.6 buggy warnings about Exception.message
125 # silence Python 2.6 buggy warnings about Exception.message
130 if _sys.version_info[:2] == (2, 6):
126 if _sys.version_info[:2] == (2, 6):
131 import warnings
127 import warnings
132 warnings.filterwarnings(
128 warnings.filterwarnings(
133 action='ignore',
129 action='ignore',
134 message='BaseException.message has been deprecated as of Python 2.6',
130 message='BaseException.message has been deprecated as of Python 2.6',
135 category=DeprecationWarning,
131 category=DeprecationWarning,
136 module='argparse')
132 module='argparse')
137
133
138
134
139 SUPPRESS = '==SUPPRESS=='
135 SUPPRESS = '==SUPPRESS=='
140
136
141 OPTIONAL = '?'
137 OPTIONAL = '?'
142 ZERO_OR_MORE = '*'
138 ZERO_OR_MORE = '*'
143 ONE_OR_MORE = '+'
139 ONE_OR_MORE = '+'
144 PARSER = '==PARSER=='
140 PARSER = 'A...'
141 REMAINDER = '...'
145
142
146 # =============================
143 # =============================
147 # Utility functions and classes
144 # Utility functions and classes
148 # =============================
145 # =============================
149
146
150 class _AttributeHolder(object):
147 class _AttributeHolder(object):
151 """Abstract base class that provides __repr__.
148 """Abstract base class that provides __repr__.
152
149
153 The __repr__ method returns a string in the format::
150 The __repr__ method returns a string in the format::
154 ClassName(attr=name, attr=name, ...)
151 ClassName(attr=name, attr=name, ...)
155 The attributes are determined either by a class-level attribute,
152 The attributes are determined either by a class-level attribute,
156 '_kwarg_names', or by inspecting the instance __dict__.
153 '_kwarg_names', or by inspecting the instance __dict__.
157 """
154 """
158
155
159 def __repr__(self):
156 def __repr__(self):
160 type_name = type(self).__name__
157 type_name = type(self).__name__
161 arg_strings = []
158 arg_strings = []
162 for arg in self._get_args():
159 for arg in self._get_args():
163 arg_strings.append(repr(arg))
160 arg_strings.append(repr(arg))
164 for name, value in self._get_kwargs():
161 for name, value in self._get_kwargs():
165 arg_strings.append('%s=%r' % (name, value))
162 arg_strings.append('%s=%r' % (name, value))
166 return '%s(%s)' % (type_name, ', '.join(arg_strings))
163 return '%s(%s)' % (type_name, ', '.join(arg_strings))
167
164
168 def _get_kwargs(self):
165 def _get_kwargs(self):
169 return _sorted(self.__dict__.items())
166 return _sorted(self.__dict__.items())
170
167
171 def _get_args(self):
168 def _get_args(self):
172 return []
169 return []
173
170
174
171
175 def _ensure_value(namespace, name, value):
172 def _ensure_value(namespace, name, value):
176 if getattr(namespace, name, None) is None:
173 if getattr(namespace, name, None) is None:
177 setattr(namespace, name, value)
174 setattr(namespace, name, value)
178 return getattr(namespace, name)
175 return getattr(namespace, name)
179
176
180
177
181 # ===============
178 # ===============
182 # Formatting Help
179 # Formatting Help
183 # ===============
180 # ===============
184
181
185 class HelpFormatter(object):
182 class HelpFormatter(object):
186 """Formatter for generating usage messages and argument help strings.
183 """Formatter for generating usage messages and argument help strings.
187
184
188 Only the name of this class is considered a public API. All the methods
185 Only the name of this class is considered a public API. All the methods
189 provided by the class are considered an implementation detail.
186 provided by the class are considered an implementation detail.
190 """
187 """
191
188
192 def __init__(self,
189 def __init__(self,
193 prog,
190 prog,
194 indent_increment=2,
191 indent_increment=2,
195 max_help_position=24,
192 max_help_position=24,
196 width=None):
193 width=None):
197
194
198 # default setting for width
195 # default setting for width
199 if width is None:
196 if width is None:
200 try:
197 try:
201 width = int(_os.environ['COLUMNS'])
198 width = int(_os.environ['COLUMNS'])
202 except (KeyError, ValueError):
199 except (KeyError, ValueError):
203 width = 80
200 width = 80
204 width -= 2
201 width -= 2
205
202
206 self._prog = prog
203 self._prog = prog
207 self._indent_increment = indent_increment
204 self._indent_increment = indent_increment
208 self._max_help_position = max_help_position
205 self._max_help_position = max_help_position
209 self._width = width
206 self._width = width
210
207
211 self._current_indent = 0
208 self._current_indent = 0
212 self._level = 0
209 self._level = 0
213 self._action_max_length = 0
210 self._action_max_length = 0
214
211
215 self._root_section = self._Section(self, None)
212 self._root_section = self._Section(self, None)
216 self._current_section = self._root_section
213 self._current_section = self._root_section
217
214
218 self._whitespace_matcher = _re.compile(r'\s+')
215 self._whitespace_matcher = _re.compile(r'\s+')
219 self._long_break_matcher = _re.compile(r'\n\n\n+')
216 self._long_break_matcher = _re.compile(r'\n\n\n+')
220
217
221 # ===============================
218 # ===============================
222 # Section and indentation methods
219 # Section and indentation methods
223 # ===============================
220 # ===============================
224 def _indent(self):
221 def _indent(self):
225 self._current_indent += self._indent_increment
222 self._current_indent += self._indent_increment
226 self._level += 1
223 self._level += 1
227
224
228 def _dedent(self):
225 def _dedent(self):
229 self._current_indent -= self._indent_increment
226 self._current_indent -= self._indent_increment
230 assert self._current_indent >= 0, 'Indent decreased below 0.'
227 assert self._current_indent >= 0, 'Indent decreased below 0.'
231 self._level -= 1
228 self._level -= 1
232
229
233 class _Section(object):
230 class _Section(object):
234
231
235 def __init__(self, formatter, parent, heading=None):
232 def __init__(self, formatter, parent, heading=None):
236 self.formatter = formatter
233 self.formatter = formatter
237 self.parent = parent
234 self.parent = parent
238 self.heading = heading
235 self.heading = heading
239 self.items = []
236 self.items = []
240
237
241 def format_help(self):
238 def format_help(self):
242 # format the indented section
239 # format the indented section
243 if self.parent is not None:
240 if self.parent is not None:
244 self.formatter._indent()
241 self.formatter._indent()
245 join = self.formatter._join_parts
242 join = self.formatter._join_parts
246 for func, args in self.items:
243 for func, args in self.items:
247 func(*args)
244 func(*args)
248 item_help = join([func(*args) for func, args in self.items])
245 item_help = join([func(*args) for func, args in self.items])
249 if self.parent is not None:
246 if self.parent is not None:
250 self.formatter._dedent()
247 self.formatter._dedent()
251
248
252 # return nothing if the section was empty
249 # return nothing if the section was empty
253 if not item_help:
250 if not item_help:
254 return ''
251 return ''
255
252
256 # add the heading if the section was non-empty
253 # add the heading if the section was non-empty
257 if self.heading is not SUPPRESS and self.heading is not None:
254 if self.heading is not SUPPRESS and self.heading is not None:
258 current_indent = self.formatter._current_indent
255 current_indent = self.formatter._current_indent
259 heading = '%*s%s:\n' % (current_indent, '', self.heading)
256 heading = '%*s%s:\n' % (current_indent, '', self.heading)
260 else:
257 else:
261 heading = ''
258 heading = ''
262
259
263 # join the section-initial newline, the heading and the help
260 # join the section-initial newline, the heading and the help
264 return join(['\n', heading, item_help, '\n'])
261 return join(['\n', heading, item_help, '\n'])
265
262
266 def _add_item(self, func, args):
263 def _add_item(self, func, args):
267 self._current_section.items.append((func, args))
264 self._current_section.items.append((func, args))
268
265
269 # ========================
266 # ========================
270 # Message building methods
267 # Message building methods
271 # ========================
268 # ========================
272 def start_section(self, heading):
269 def start_section(self, heading):
273 self._indent()
270 self._indent()
274 section = self._Section(self, self._current_section, heading)
271 section = self._Section(self, self._current_section, heading)
275 self._add_item(section.format_help, [])
272 self._add_item(section.format_help, [])
276 self._current_section = section
273 self._current_section = section
277
274
278 def end_section(self):
275 def end_section(self):
279 self._current_section = self._current_section.parent
276 self._current_section = self._current_section.parent
280 self._dedent()
277 self._dedent()
281
278
282 def add_text(self, text):
279 def add_text(self, text):
283 if text is not SUPPRESS and text is not None:
280 if text is not SUPPRESS and text is not None:
284 self._add_item(self._format_text, [text])
281 self._add_item(self._format_text, [text])
285
282
286 def add_usage(self, usage, actions, groups, prefix=None):
283 def add_usage(self, usage, actions, groups, prefix=None):
287 if usage is not SUPPRESS:
284 if usage is not SUPPRESS:
288 args = usage, actions, groups, prefix
285 args = usage, actions, groups, prefix
289 self._add_item(self._format_usage, args)
286 self._add_item(self._format_usage, args)
290
287
291 def add_argument(self, action):
288 def add_argument(self, action):
292 if action.help is not SUPPRESS:
289 if action.help is not SUPPRESS:
293
290
294 # find all invocations
291 # find all invocations
295 get_invocation = self._format_action_invocation
292 get_invocation = self._format_action_invocation
296 invocations = [get_invocation(action)]
293 invocations = [get_invocation(action)]
297 for subaction in self._iter_indented_subactions(action):
294 for subaction in self._iter_indented_subactions(action):
298 invocations.append(get_invocation(subaction))
295 invocations.append(get_invocation(subaction))
299
296
300 # update the maximum item length
297 # update the maximum item length
301 invocation_length = max([len(s) for s in invocations])
298 invocation_length = max([len(s) for s in invocations])
302 action_length = invocation_length + self._current_indent
299 action_length = invocation_length + self._current_indent
303 self._action_max_length = max(self._action_max_length,
300 self._action_max_length = max(self._action_max_length,
304 action_length)
301 action_length)
305
302
306 # add the item to the list
303 # add the item to the list
307 self._add_item(self._format_action, [action])
304 self._add_item(self._format_action, [action])
308
305
309 def add_arguments(self, actions):
306 def add_arguments(self, actions):
310 for action in actions:
307 for action in actions:
311 self.add_argument(action)
308 self.add_argument(action)
312
309
313 # =======================
310 # =======================
314 # Help-formatting methods
311 # Help-formatting methods
315 # =======================
312 # =======================
316 def format_help(self):
313 def format_help(self):
317 help = self._root_section.format_help()
314 help = self._root_section.format_help()
318 if help:
315 if help:
319 help = self._long_break_matcher.sub('\n\n', help)
316 help = self._long_break_matcher.sub('\n\n', help)
320 help = help.strip('\n') + '\n'
317 help = help.strip('\n') + '\n'
321 return help
318 return help
322
319
323 def _join_parts(self, part_strings):
320 def _join_parts(self, part_strings):
324 return ''.join([part
321 return ''.join([part
325 for part in part_strings
322 for part in part_strings
326 if part and part is not SUPPRESS])
323 if part and part is not SUPPRESS])
327
324
328 def _format_usage(self, usage, actions, groups, prefix):
325 def _format_usage(self, usage, actions, groups, prefix):
329 if prefix is None:
326 if prefix is None:
330 prefix = _('usage: ')
327 prefix = _('usage: ')
331
328
332 # if usage is specified, use that
329 # if usage is specified, use that
333 if usage is not None:
330 if usage is not None:
334 usage = usage % dict(prog=self._prog)
331 usage = usage % dict(prog=self._prog)
335
332
336 # if no optionals or positionals are available, usage is just prog
333 # if no optionals or positionals are available, usage is just prog
337 elif usage is None and not actions:
334 elif usage is None and not actions:
338 usage = '%(prog)s' % dict(prog=self._prog)
335 usage = '%(prog)s' % dict(prog=self._prog)
339
336
340 # if optionals and positionals are available, calculate usage
337 # if optionals and positionals are available, calculate usage
341 elif usage is None:
338 elif usage is None:
342 prog = '%(prog)s' % dict(prog=self._prog)
339 prog = '%(prog)s' % dict(prog=self._prog)
343
340
344 # split optionals from positionals
341 # split optionals from positionals
345 optionals = []
342 optionals = []
346 positionals = []
343 positionals = []
347 for action in actions:
344 for action in actions:
348 if action.option_strings:
345 if action.option_strings:
349 optionals.append(action)
346 optionals.append(action)
350 else:
347 else:
351 positionals.append(action)
348 positionals.append(action)
352
349
353 # build full usage string
350 # build full usage string
354 format = self._format_actions_usage
351 format = self._format_actions_usage
355 action_usage = format(optionals + positionals, groups)
352 action_usage = format(optionals + positionals, groups)
356 usage = ' '.join([s for s in [prog, action_usage] if s])
353 usage = ' '.join([s for s in [prog, action_usage] if s])
357
354
358 # wrap the usage parts if it's too long
355 # wrap the usage parts if it's too long
359 text_width = self._width - self._current_indent
356 text_width = self._width - self._current_indent
360 if len(prefix) + len(usage) > text_width:
357 if len(prefix) + len(usage) > text_width:
361
358
362 # break usage into wrappable parts
359 # break usage into wrappable parts
363 part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
360 part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
364 opt_usage = format(optionals, groups)
361 opt_usage = format(optionals, groups)
365 pos_usage = format(positionals, groups)
362 pos_usage = format(positionals, groups)
366 opt_parts = _re.findall(part_regexp, opt_usage)
363 opt_parts = _re.findall(part_regexp, opt_usage)
367 pos_parts = _re.findall(part_regexp, pos_usage)
364 pos_parts = _re.findall(part_regexp, pos_usage)
368 assert ' '.join(opt_parts) == opt_usage
365 assert ' '.join(opt_parts) == opt_usage
369 assert ' '.join(pos_parts) == pos_usage
366 assert ' '.join(pos_parts) == pos_usage
370
367
371 # helper for wrapping lines
368 # helper for wrapping lines
372 def get_lines(parts, indent, prefix=None):
369 def get_lines(parts, indent, prefix=None):
373 lines = []
370 lines = []
374 line = []
371 line = []
375 if prefix is not None:
372 if prefix is not None:
376 line_len = len(prefix) - 1
373 line_len = len(prefix) - 1
377 else:
374 else:
378 line_len = len(indent) - 1
375 line_len = len(indent) - 1
379 for part in parts:
376 for part in parts:
380 if line_len + 1 + len(part) > text_width:
377 if line_len + 1 + len(part) > text_width:
381 lines.append(indent + ' '.join(line))
378 lines.append(indent + ' '.join(line))
382 line = []
379 line = []
383 line_len = len(indent) - 1
380 line_len = len(indent) - 1
384 line.append(part)
381 line.append(part)
385 line_len += len(part) + 1
382 line_len += len(part) + 1
386 if line:
383 if line:
387 lines.append(indent + ' '.join(line))
384 lines.append(indent + ' '.join(line))
388 if prefix is not None:
385 if prefix is not None:
389 lines[0] = lines[0][len(indent):]
386 lines[0] = lines[0][len(indent):]
390 return lines
387 return lines
391
388
392 # if prog is short, follow it with optionals or positionals
389 # if prog is short, follow it with optionals or positionals
393 if len(prefix) + len(prog) <= 0.75 * text_width:
390 if len(prefix) + len(prog) <= 0.75 * text_width:
394 indent = ' ' * (len(prefix) + len(prog) + 1)
391 indent = ' ' * (len(prefix) + len(prog) + 1)
395 if opt_parts:
392 if opt_parts:
396 lines = get_lines([prog] + opt_parts, indent, prefix)
393 lines = get_lines([prog] + opt_parts, indent, prefix)
397 lines.extend(get_lines(pos_parts, indent))
394 lines.extend(get_lines(pos_parts, indent))
398 elif pos_parts:
395 elif pos_parts:
399 lines = get_lines([prog] + pos_parts, indent, prefix)
396 lines = get_lines([prog] + pos_parts, indent, prefix)
400 else:
397 else:
401 lines = [prog]
398 lines = [prog]
402
399
403 # if prog is long, put it on its own line
400 # if prog is long, put it on its own line
404 else:
401 else:
405 indent = ' ' * len(prefix)
402 indent = ' ' * len(prefix)
406 parts = opt_parts + pos_parts
403 parts = opt_parts + pos_parts
407 lines = get_lines(parts, indent)
404 lines = get_lines(parts, indent)
408 if len(lines) > 1:
405 if len(lines) > 1:
409 lines = []
406 lines = []
410 lines.extend(get_lines(opt_parts, indent))
407 lines.extend(get_lines(opt_parts, indent))
411 lines.extend(get_lines(pos_parts, indent))
408 lines.extend(get_lines(pos_parts, indent))
412 lines = [prog] + lines
409 lines = [prog] + lines
413
410
414 # join lines into usage
411 # join lines into usage
415 usage = '\n'.join(lines)
412 usage = '\n'.join(lines)
416
413
417 # prefix with 'usage:'
414 # prefix with 'usage:'
418 return '%s%s\n\n' % (prefix, usage)
415 return '%s%s\n\n' % (prefix, usage)
419
416
420 def _format_actions_usage(self, actions, groups):
417 def _format_actions_usage(self, actions, groups):
421 # find group indices and identify actions in groups
418 # find group indices and identify actions in groups
422 group_actions = _set()
419 group_actions = _set()
423 inserts = {}
420 inserts = {}
424 for group in groups:
421 for group in groups:
425 try:
422 try:
426 start = actions.index(group._group_actions[0])
423 start = actions.index(group._group_actions[0])
427 except ValueError:
424 except ValueError:
428 continue
425 continue
429 else:
426 else:
430 end = start + len(group._group_actions)
427 end = start + len(group._group_actions)
431 if actions[start:end] == group._group_actions:
428 if actions[start:end] == group._group_actions:
432 for action in group._group_actions:
429 for action in group._group_actions:
433 group_actions.add(action)
430 group_actions.add(action)
434 if not group.required:
431 if not group.required:
435 inserts[start] = '['
432 inserts[start] = '['
436 inserts[end] = ']'
433 inserts[end] = ']'
437 else:
434 else:
438 inserts[start] = '('
435 inserts[start] = '('
439 inserts[end] = ')'
436 inserts[end] = ')'
440 for i in range(start + 1, end):
437 for i in range(start + 1, end):
441 inserts[i] = '|'
438 inserts[i] = '|'
442
439
443 # collect all actions format strings
440 # collect all actions format strings
444 parts = []
441 parts = []
445 for i, action in enumerate(actions):
442 for i, action in enumerate(actions):
446
443
447 # suppressed arguments are marked with None
444 # suppressed arguments are marked with None
448 # remove | separators for suppressed arguments
445 # remove | separators for suppressed arguments
449 if action.help is SUPPRESS:
446 if action.help is SUPPRESS:
450 parts.append(None)
447 parts.append(None)
451 if inserts.get(i) == '|':
448 if inserts.get(i) == '|':
452 inserts.pop(i)
449 inserts.pop(i)
453 elif inserts.get(i + 1) == '|':
450 elif inserts.get(i + 1) == '|':
454 inserts.pop(i + 1)
451 inserts.pop(i + 1)
455
452
456 # produce all arg strings
453 # produce all arg strings
457 elif not action.option_strings:
454 elif not action.option_strings:
458 part = self._format_args(action, action.dest)
455 part = self._format_args(action, action.dest)
459
456
460 # if it's in a group, strip the outer []
457 # if it's in a group, strip the outer []
461 if action in group_actions:
458 if action in group_actions:
462 if part[0] == '[' and part[-1] == ']':
459 if part[0] == '[' and part[-1] == ']':
463 part = part[1:-1]
460 part = part[1:-1]
464
461
465 # add the action string to the list
462 # add the action string to the list
466 parts.append(part)
463 parts.append(part)
467
464
468 # produce the first way to invoke the option in brackets
465 # produce the first way to invoke the option in brackets
469 else:
466 else:
470 option_string = action.option_strings[0]
467 option_string = action.option_strings[0]
471
468
472 # if the Optional doesn't take a value, format is:
469 # if the Optional doesn't take a value, format is:
473 # -s or --long
470 # -s or --long
474 if action.nargs == 0:
471 if action.nargs == 0:
475 part = '%s' % option_string
472 part = '%s' % option_string
476
473
477 # if the Optional takes a value, format is:
474 # if the Optional takes a value, format is:
478 # -s ARGS or --long ARGS
475 # -s ARGS or --long ARGS
479 else:
476 else:
480 default = action.dest.upper()
477 default = action.dest.upper()
481 args_string = self._format_args(action, default)
478 args_string = self._format_args(action, default)
482 part = '%s %s' % (option_string, args_string)
479 part = '%s %s' % (option_string, args_string)
483
480
484 # make it look optional if it's not required or in a group
481 # make it look optional if it's not required or in a group
485 if not action.required and action not in group_actions:
482 if not action.required and action not in group_actions:
486 part = '[%s]' % part
483 part = '[%s]' % part
487
484
488 # add the action string to the list
485 # add the action string to the list
489 parts.append(part)
486 parts.append(part)
490
487
491 # insert things at the necessary indices
488 # insert things at the necessary indices
492 for i in _sorted(inserts, reverse=True):
489 for i in _sorted(inserts, reverse=True):
493 parts[i:i] = [inserts[i]]
490 parts[i:i] = [inserts[i]]
494
491
495 # join all the action items with spaces
492 # join all the action items with spaces
496 text = ' '.join([item for item in parts if item is not None])
493 text = ' '.join([item for item in parts if item is not None])
497
494
498 # clean up separators for mutually exclusive groups
495 # clean up separators for mutually exclusive groups
499 open = r'[\[(]'
496 open = r'[\[(]'
500 close = r'[\])]'
497 close = r'[\])]'
501 text = _re.sub(r'(%s) ' % open, r'\1', text)
498 text = _re.sub(r'(%s) ' % open, r'\1', text)
502 text = _re.sub(r' (%s)' % close, r'\1', text)
499 text = _re.sub(r' (%s)' % close, r'\1', text)
503 text = _re.sub(r'%s *%s' % (open, close), r'', text)
500 text = _re.sub(r'%s *%s' % (open, close), r'', text)
504 text = _re.sub(r'\(([^|]*)\)', r'\1', text)
501 text = _re.sub(r'\(([^|]*)\)', r'\1', text)
505 text = text.strip()
502 text = text.strip()
506
503
507 # return the text
504 # return the text
508 return text
505 return text
509
506
510 def _format_text(self, text):
507 def _format_text(self, text):
508 if '%(prog)' in text:
509 text = text % dict(prog=self._prog)
511 text_width = self._width - self._current_indent
510 text_width = self._width - self._current_indent
512 indent = ' ' * self._current_indent
511 indent = ' ' * self._current_indent
513 return self._fill_text(text, text_width, indent) + '\n\n'
512 return self._fill_text(text, text_width, indent) + '\n\n'
514
513
515 def _format_action(self, action):
514 def _format_action(self, action):
516 # determine the required width and the entry label
515 # determine the required width and the entry label
517 help_position = min(self._action_max_length + 2,
516 help_position = min(self._action_max_length + 2,
518 self._max_help_position)
517 self._max_help_position)
519 help_width = self._width - help_position
518 help_width = self._width - help_position
520 action_width = help_position - self._current_indent - 2
519 action_width = help_position - self._current_indent - 2
521 action_header = self._format_action_invocation(action)
520 action_header = self._format_action_invocation(action)
522
521
523 # ho nelp; start on same line and add a final newline
522 # ho nelp; start on same line and add a final newline
524 if not action.help:
523 if not action.help:
525 tup = self._current_indent, '', action_header
524 tup = self._current_indent, '', action_header
526 action_header = '%*s%s\n' % tup
525 action_header = '%*s%s\n' % tup
527
526
528 # short action name; start on the same line and pad two spaces
527 # short action name; start on the same line and pad two spaces
529 elif len(action_header) <= action_width:
528 elif len(action_header) <= action_width:
530 tup = self._current_indent, '', action_width, action_header
529 tup = self._current_indent, '', action_width, action_header
531 action_header = '%*s%-*s ' % tup
530 action_header = '%*s%-*s ' % tup
532 indent_first = 0
531 indent_first = 0
533
532
534 # long action name; start on the next line
533 # long action name; start on the next line
535 else:
534 else:
536 tup = self._current_indent, '', action_header
535 tup = self._current_indent, '', action_header
537 action_header = '%*s%s\n' % tup
536 action_header = '%*s%s\n' % tup
538 indent_first = help_position
537 indent_first = help_position
539
538
540 # collect the pieces of the action help
539 # collect the pieces of the action help
541 parts = [action_header]
540 parts = [action_header]
542
541
543 # if there was help for the action, add lines of help text
542 # if there was help for the action, add lines of help text
544 if action.help:
543 if action.help:
545 help_text = self._expand_help(action)
544 help_text = self._expand_help(action)
546 help_lines = self._split_lines(help_text, help_width)
545 help_lines = self._split_lines(help_text, help_width)
547 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
546 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
548 for line in help_lines[1:]:
547 for line in help_lines[1:]:
549 parts.append('%*s%s\n' % (help_position, '', line))
548 parts.append('%*s%s\n' % (help_position, '', line))
550
549
551 # or add a newline if the description doesn't end with one
550 # or add a newline if the description doesn't end with one
552 elif not action_header.endswith('\n'):
551 elif not action_header.endswith('\n'):
553 parts.append('\n')
552 parts.append('\n')
554
553
555 # if there are any sub-actions, add their help as well
554 # if there are any sub-actions, add their help as well
556 for subaction in self._iter_indented_subactions(action):
555 for subaction in self._iter_indented_subactions(action):
557 parts.append(self._format_action(subaction))
556 parts.append(self._format_action(subaction))
558
557
559 # return a single string
558 # return a single string
560 return self._join_parts(parts)
559 return self._join_parts(parts)
561
560
562 def _format_action_invocation(self, action):
561 def _format_action_invocation(self, action):
563 if not action.option_strings:
562 if not action.option_strings:
564 metavar, = self._metavar_formatter(action, action.dest)(1)
563 metavar, = self._metavar_formatter(action, action.dest)(1)
565 return metavar
564 return metavar
566
565
567 else:
566 else:
568 parts = []
567 parts = []
569
568
570 # if the Optional doesn't take a value, format is:
569 # if the Optional doesn't take a value, format is:
571 # -s, --long
570 # -s, --long
572 if action.nargs == 0:
571 if action.nargs == 0:
573 parts.extend(action.option_strings)
572 parts.extend(action.option_strings)
574
573
575 # if the Optional takes a value, format is:
574 # if the Optional takes a value, format is:
576 # -s ARGS, --long ARGS
575 # -s ARGS, --long ARGS
577 else:
576 else:
578 default = action.dest.upper()
577 default = action.dest.upper()
579 args_string = self._format_args(action, default)
578 args_string = self._format_args(action, default)
580 for option_string in action.option_strings:
579 for option_string in action.option_strings:
581 parts.append('%s %s' % (option_string, args_string))
580 parts.append('%s %s' % (option_string, args_string))
582
581
583 return ', '.join(parts)
582 return ', '.join(parts)
584
583
585 def _metavar_formatter(self, action, default_metavar):
584 def _metavar_formatter(self, action, default_metavar):
586 if action.metavar is not None:
585 if action.metavar is not None:
587 result = action.metavar
586 result = action.metavar
588 elif action.choices is not None:
587 elif action.choices is not None:
589 choice_strs = [str(choice) for choice in action.choices]
588 choice_strs = [str(choice) for choice in action.choices]
590 result = '{%s}' % ','.join(choice_strs)
589 result = '{%s}' % ','.join(choice_strs)
591 else:
590 else:
592 result = default_metavar
591 result = default_metavar
593
592
594 def format(tuple_size):
593 def format(tuple_size):
595 if isinstance(result, tuple):
594 if isinstance(result, tuple):
596 return result
595 return result
597 else:
596 else:
598 return (result, ) * tuple_size
597 return (result, ) * tuple_size
599 return format
598 return format
600
599
601 def _format_args(self, action, default_metavar):
600 def _format_args(self, action, default_metavar):
602 get_metavar = self._metavar_formatter(action, default_metavar)
601 get_metavar = self._metavar_formatter(action, default_metavar)
603 if action.nargs is None:
602 if action.nargs is None:
604 result = '%s' % get_metavar(1)
603 result = '%s' % get_metavar(1)
605 elif action.nargs == OPTIONAL:
604 elif action.nargs == OPTIONAL:
606 result = '[%s]' % get_metavar(1)
605 result = '[%s]' % get_metavar(1)
607 elif action.nargs == ZERO_OR_MORE:
606 elif action.nargs == ZERO_OR_MORE:
608 result = '[%s [%s ...]]' % get_metavar(2)
607 result = '[%s [%s ...]]' % get_metavar(2)
609 elif action.nargs == ONE_OR_MORE:
608 elif action.nargs == ONE_OR_MORE:
610 result = '%s [%s ...]' % get_metavar(2)
609 result = '%s [%s ...]' % get_metavar(2)
611 elif action.nargs is PARSER:
610 elif action.nargs == REMAINDER:
611 result = '...'
612 elif action.nargs == PARSER:
612 result = '%s ...' % get_metavar(1)
613 result = '%s ...' % get_metavar(1)
613 else:
614 else:
614 formats = ['%s' for _ in range(action.nargs)]
615 formats = ['%s' for _ in range(action.nargs)]
615 result = ' '.join(formats) % get_metavar(action.nargs)
616 result = ' '.join(formats) % get_metavar(action.nargs)
616 return result
617 return result
617
618
618 def _expand_help(self, action):
619 def _expand_help(self, action):
619 params = dict(vars(action), prog=self._prog)
620 params = dict(vars(action), prog=self._prog)
620 for name in list(params):
621 for name in list(params):
621 if params[name] is SUPPRESS:
622 if params[name] is SUPPRESS:
622 del params[name]
623 del params[name]
623 if params.get('choices') is not None:
624 if params.get('choices') is not None:
624 choices_str = ', '.join([str(c) for c in params['choices']])
625 choices_str = ', '.join([str(c) for c in params['choices']])
625 params['choices'] = choices_str
626 params['choices'] = choices_str
626 return self._get_help_string(action) % params
627 return self._get_help_string(action) % params
627
628
628 def _iter_indented_subactions(self, action):
629 def _iter_indented_subactions(self, action):
629 try:
630 try:
630 get_subactions = action._get_subactions
631 get_subactions = action._get_subactions
631 except AttributeError:
632 except AttributeError:
632 pass
633 pass
633 else:
634 else:
634 self._indent()
635 self._indent()
635 for subaction in get_subactions():
636 for subaction in get_subactions():
636 yield subaction
637 yield subaction
637 self._dedent()
638 self._dedent()
638
639
639 def _split_lines(self, text, width):
640 def _split_lines(self, text, width):
640 text = self._whitespace_matcher.sub(' ', text).strip()
641 text = self._whitespace_matcher.sub(' ', text).strip()
641 return _textwrap.wrap(text, width)
642 return _textwrap.wrap(text, width)
642
643
643 def _fill_text(self, text, width, indent):
644 def _fill_text(self, text, width, indent):
644 text = self._whitespace_matcher.sub(' ', text).strip()
645 text = self._whitespace_matcher.sub(' ', text).strip()
645 return _textwrap.fill(text, width, initial_indent=indent,
646 return _textwrap.fill(text, width, initial_indent=indent,
646 subsequent_indent=indent)
647 subsequent_indent=indent)
647
648
648 def _get_help_string(self, action):
649 def _get_help_string(self, action):
649 return action.help
650 return action.help
650
651
651
652
652 class RawDescriptionHelpFormatter(HelpFormatter):
653 class RawDescriptionHelpFormatter(HelpFormatter):
653 """Help message formatter which retains any formatting in descriptions.
654 """Help message formatter which retains any formatting in descriptions.
654
655
655 Only the name of this class is considered a public API. All the methods
656 Only the name of this class is considered a public API. All the methods
656 provided by the class are considered an implementation detail.
657 provided by the class are considered an implementation detail.
657 """
658 """
658
659
659 def _fill_text(self, text, width, indent):
660 def _fill_text(self, text, width, indent):
660 return ''.join([indent + line for line in text.splitlines(True)])
661 return ''.join([indent + line for line in text.splitlines(True)])
661
662
662
663
663 class RawTextHelpFormatter(RawDescriptionHelpFormatter):
664 class RawTextHelpFormatter(RawDescriptionHelpFormatter):
664 """Help message formatter which retains formatting of all help text.
665 """Help message formatter which retains formatting of all help text.
665
666
666 Only the name of this class is considered a public API. All the methods
667 Only the name of this class is considered a public API. All the methods
667 provided by the class are considered an implementation detail.
668 provided by the class are considered an implementation detail.
668 """
669 """
669
670
670 def _split_lines(self, text, width):
671 def _split_lines(self, text, width):
671 return text.splitlines()
672 return text.splitlines()
672
673
673
674
674 class ArgumentDefaultsHelpFormatter(HelpFormatter):
675 class ArgumentDefaultsHelpFormatter(HelpFormatter):
675 """Help message formatter which adds default values to argument help.
676 """Help message formatter which adds default values to argument help.
676
677
677 Only the name of this class is considered a public API. All the methods
678 Only the name of this class is considered a public API. All the methods
678 provided by the class are considered an implementation detail.
679 provided by the class are considered an implementation detail.
679 """
680 """
680
681
681 def _get_help_string(self, action):
682 def _get_help_string(self, action):
682 help = action.help
683 help = action.help
683 if '%(default)' not in action.help:
684 if '%(default)' not in action.help:
684 if action.default is not SUPPRESS:
685 if action.default is not SUPPRESS:
685 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
686 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
686 if action.option_strings or action.nargs in defaulting_nargs:
687 if action.option_strings or action.nargs in defaulting_nargs:
687 help += ' (default: %(default)s)'
688 help += ' (default: %(default)s)'
688 return help
689 return help
689
690
690
691
691 # =====================
692 # =====================
692 # Options and Arguments
693 # Options and Arguments
693 # =====================
694 # =====================
694
695
695 def _get_action_name(argument):
696 def _get_action_name(argument):
696 if argument is None:
697 if argument is None:
697 return None
698 return None
698 elif argument.option_strings:
699 elif argument.option_strings:
699 return '/'.join(argument.option_strings)
700 return '/'.join(argument.option_strings)
700 elif argument.metavar not in (None, SUPPRESS):
701 elif argument.metavar not in (None, SUPPRESS):
701 return argument.metavar
702 return argument.metavar
702 elif argument.dest not in (None, SUPPRESS):
703 elif argument.dest not in (None, SUPPRESS):
703 return argument.dest
704 return argument.dest
704 else:
705 else:
705 return None
706 return None
706
707
707
708
708 class ArgumentError(Exception):
709 class ArgumentError(Exception):
709 """An error from creating or using an argument (optional or positional).
710 """An error from creating or using an argument (optional or positional).
710
711
711 The string value of this exception is the message, augmented with
712 The string value of this exception is the message, augmented with
712 information about the argument that caused it.
713 information about the argument that caused it.
713 """
714 """
714
715
715 def __init__(self, argument, message):
716 def __init__(self, argument, message):
716 self.argument_name = _get_action_name(argument)
717 self.argument_name = _get_action_name(argument)
717 self.message = message
718 self.message = message
718
719
719 def __str__(self):
720 def __str__(self):
720 if self.argument_name is None:
721 if self.argument_name is None:
721 format = '%(message)s'
722 format = '%(message)s'
722 else:
723 else:
723 format = 'argument %(argument_name)s: %(message)s'
724 format = 'argument %(argument_name)s: %(message)s'
724 return format % dict(message=self.message,
725 return format % dict(message=self.message,
725 argument_name=self.argument_name)
726 argument_name=self.argument_name)
726
727
728
729 class ArgumentTypeError(Exception):
730 """An error from trying to convert a command line string to a type."""
731 pass
732
733
727 # ==============
734 # ==============
728 # Action classes
735 # Action classes
729 # ==============
736 # ==============
730
737
731 class Action(_AttributeHolder):
738 class Action(_AttributeHolder):
732 """Information about how to convert command line strings to Python objects.
739 """Information about how to convert command line strings to Python objects.
733
740
734 Action objects are used by an ArgumentParser to represent the information
741 Action objects are used by an ArgumentParser to represent the information
735 needed to parse a single argument from one or more strings from the
742 needed to parse a single argument from one or more strings from the
736 command line. The keyword arguments to the Action constructor are also
743 command line. The keyword arguments to the Action constructor are also
737 all attributes of Action instances.
744 all attributes of Action instances.
738
745
739 Keyword Arguments:
746 Keyword Arguments:
740
747
741 - option_strings -- A list of command-line option strings which
748 - option_strings -- A list of command-line option strings which
742 should be associated with this action.
749 should be associated with this action.
743
750
744 - dest -- The name of the attribute to hold the created object(s)
751 - dest -- The name of the attribute to hold the created object(s)
745
752
746 - nargs -- The number of command-line arguments that should be
753 - nargs -- The number of command-line arguments that should be
747 consumed. By default, one argument will be consumed and a single
754 consumed. By default, one argument will be consumed and a single
748 value will be produced. Other values include:
755 value will be produced. Other values include:
749 - N (an integer) consumes N arguments (and produces a list)
756 - N (an integer) consumes N arguments (and produces a list)
750 - '?' consumes zero or one arguments
757 - '?' consumes zero or one arguments
751 - '*' consumes zero or more arguments (and produces a list)
758 - '*' consumes zero or more arguments (and produces a list)
752 - '+' consumes one or more arguments (and produces a list)
759 - '+' consumes one or more arguments (and produces a list)
753 Note that the difference between the default and nargs=1 is that
760 Note that the difference between the default and nargs=1 is that
754 with the default, a single value will be produced, while with
761 with the default, a single value will be produced, while with
755 nargs=1, a list containing a single value will be produced.
762 nargs=1, a list containing a single value will be produced.
756
763
757 - const -- The value to be produced if the option is specified and the
764 - const -- The value to be produced if the option is specified and the
758 option uses an action that takes no values.
765 option uses an action that takes no values.
759
766
760 - default -- The value to be produced if the option is not specified.
767 - default -- The value to be produced if the option is not specified.
761
768
762 - type -- The type which the command-line arguments should be converted
769 - type -- The type which the command-line arguments should be converted
763 to, should be one of 'string', 'int', 'float', 'complex' or a
770 to, should be one of 'string', 'int', 'float', 'complex' or a
764 callable object that accepts a single string argument. If None,
771 callable object that accepts a single string argument. If None,
765 'string' is assumed.
772 'string' is assumed.
766
773
767 - choices -- A container of values that should be allowed. If not None,
774 - choices -- A container of values that should be allowed. If not None,
768 after a command-line argument has been converted to the appropriate
775 after a command-line argument has been converted to the appropriate
769 type, an exception will be raised if it is not a member of this
776 type, an exception will be raised if it is not a member of this
770 collection.
777 collection.
771
778
772 - required -- True if the action must always be specified at the
779 - required -- True if the action must always be specified at the
773 command line. This is only meaningful for optional command-line
780 command line. This is only meaningful for optional command-line
774 arguments.
781 arguments.
775
782
776 - help -- The help string describing the argument.
783 - help -- The help string describing the argument.
777
784
778 - metavar -- The name to be used for the option's argument with the
785 - metavar -- The name to be used for the option's argument with the
779 help string. If None, the 'dest' value will be used as the name.
786 help string. If None, the 'dest' value will be used as the name.
780 """
787 """
781
788
782 def __init__(self,
789 def __init__(self,
783 option_strings,
790 option_strings,
784 dest,
791 dest,
785 nargs=None,
792 nargs=None,
786 const=None,
793 const=None,
787 default=None,
794 default=None,
788 type=None,
795 type=None,
789 choices=None,
796 choices=None,
790 required=False,
797 required=False,
791 help=None,
798 help=None,
792 metavar=None):
799 metavar=None):
793 self.option_strings = option_strings
800 self.option_strings = option_strings
794 self.dest = dest
801 self.dest = dest
795 self.nargs = nargs
802 self.nargs = nargs
796 self.const = const
803 self.const = const
797 self.default = default
804 self.default = default
798 self.type = type
805 self.type = type
799 self.choices = choices
806 self.choices = choices
800 self.required = required
807 self.required = required
801 self.help = help
808 self.help = help
802 self.metavar = metavar
809 self.metavar = metavar
803
810
804 def _get_kwargs(self):
811 def _get_kwargs(self):
805 names = [
812 names = [
806 'option_strings',
813 'option_strings',
807 'dest',
814 'dest',
808 'nargs',
815 'nargs',
809 'const',
816 'const',
810 'default',
817 'default',
811 'type',
818 'type',
812 'choices',
819 'choices',
813 'help',
820 'help',
814 'metavar',
821 'metavar',
815 ]
822 ]
816 return [(name, getattr(self, name)) for name in names]
823 return [(name, getattr(self, name)) for name in names]
817
824
818 def __call__(self, parser, namespace, values, option_string=None):
825 def __call__(self, parser, namespace, values, option_string=None):
819 raise NotImplementedError(_('.__call__() not defined'))
826 raise NotImplementedError(_('.__call__() not defined'))
820
827
821
828
822 class _StoreAction(Action):
829 class _StoreAction(Action):
823
830
824 def __init__(self,
831 def __init__(self,
825 option_strings,
832 option_strings,
826 dest,
833 dest,
827 nargs=None,
834 nargs=None,
828 const=None,
835 const=None,
829 default=None,
836 default=None,
830 type=None,
837 type=None,
831 choices=None,
838 choices=None,
832 required=False,
839 required=False,
833 help=None,
840 help=None,
834 metavar=None):
841 metavar=None):
835 if nargs == 0:
842 if nargs == 0:
836 raise ValueError('nargs for store actions must be > 0; if you '
843 raise ValueError('nargs for store actions must be > 0; if you '
837 'have nothing to store, actions such as store '
844 'have nothing to store, actions such as store '
838 'true or store const may be more appropriate')
845 'true or store const may be more appropriate')
839 if const is not None and nargs != OPTIONAL:
846 if const is not None and nargs != OPTIONAL:
840 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
847 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
841 super(_StoreAction, self).__init__(
848 super(_StoreAction, self).__init__(
842 option_strings=option_strings,
849 option_strings=option_strings,
843 dest=dest,
850 dest=dest,
844 nargs=nargs,
851 nargs=nargs,
845 const=const,
852 const=const,
846 default=default,
853 default=default,
847 type=type,
854 type=type,
848 choices=choices,
855 choices=choices,
849 required=required,
856 required=required,
850 help=help,
857 help=help,
851 metavar=metavar)
858 metavar=metavar)
852
859
853 def __call__(self, parser, namespace, values, option_string=None):
860 def __call__(self, parser, namespace, values, option_string=None):
854 setattr(namespace, self.dest, values)
861 setattr(namespace, self.dest, values)
855
862
856
863
857 class _StoreConstAction(Action):
864 class _StoreConstAction(Action):
858
865
859 def __init__(self,
866 def __init__(self,
860 option_strings,
867 option_strings,
861 dest,
868 dest,
862 const,
869 const,
863 default=None,
870 default=None,
864 required=False,
871 required=False,
865 help=None,
872 help=None,
866 metavar=None):
873 metavar=None):
867 super(_StoreConstAction, self).__init__(
874 super(_StoreConstAction, self).__init__(
868 option_strings=option_strings,
875 option_strings=option_strings,
869 dest=dest,
876 dest=dest,
870 nargs=0,
877 nargs=0,
871 const=const,
878 const=const,
872 default=default,
879 default=default,
873 required=required,
880 required=required,
874 help=help)
881 help=help)
875
882
876 def __call__(self, parser, namespace, values, option_string=None):
883 def __call__(self, parser, namespace, values, option_string=None):
877 setattr(namespace, self.dest, self.const)
884 setattr(namespace, self.dest, self.const)
878
885
879
886
880 class _StoreTrueAction(_StoreConstAction):
887 class _StoreTrueAction(_StoreConstAction):
881
888
882 def __init__(self,
889 def __init__(self,
883 option_strings,
890 option_strings,
884 dest,
891 dest,
885 default=False,
892 default=False,
886 required=False,
893 required=False,
887 help=None):
894 help=None):
888 super(_StoreTrueAction, self).__init__(
895 super(_StoreTrueAction, self).__init__(
889 option_strings=option_strings,
896 option_strings=option_strings,
890 dest=dest,
897 dest=dest,
891 const=True,
898 const=True,
892 default=default,
899 default=default,
893 required=required,
900 required=required,
894 help=help)
901 help=help)
895
902
896
903
897 class _StoreFalseAction(_StoreConstAction):
904 class _StoreFalseAction(_StoreConstAction):
898
905
899 def __init__(self,
906 def __init__(self,
900 option_strings,
907 option_strings,
901 dest,
908 dest,
902 default=True,
909 default=True,
903 required=False,
910 required=False,
904 help=None):
911 help=None):
905 super(_StoreFalseAction, self).__init__(
912 super(_StoreFalseAction, self).__init__(
906 option_strings=option_strings,
913 option_strings=option_strings,
907 dest=dest,
914 dest=dest,
908 const=False,
915 const=False,
909 default=default,
916 default=default,
910 required=required,
917 required=required,
911 help=help)
918 help=help)
912
919
913
920
914 class _AppendAction(Action):
921 class _AppendAction(Action):
915
922
916 def __init__(self,
923 def __init__(self,
917 option_strings,
924 option_strings,
918 dest,
925 dest,
919 nargs=None,
926 nargs=None,
920 const=None,
927 const=None,
921 default=None,
928 default=None,
922 type=None,
929 type=None,
923 choices=None,
930 choices=None,
924 required=False,
931 required=False,
925 help=None,
932 help=None,
926 metavar=None):
933 metavar=None):
927 if nargs == 0:
934 if nargs == 0:
928 raise ValueError('nargs for append actions must be > 0; if arg '
935 raise ValueError('nargs for append actions must be > 0; if arg '
929 'strings are not supplying the value to append, '
936 'strings are not supplying the value to append, '
930 'the append const action may be more appropriate')
937 'the append const action may be more appropriate')
931 if const is not None and nargs != OPTIONAL:
938 if const is not None and nargs != OPTIONAL:
932 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
939 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
933 super(_AppendAction, self).__init__(
940 super(_AppendAction, self).__init__(
934 option_strings=option_strings,
941 option_strings=option_strings,
935 dest=dest,
942 dest=dest,
936 nargs=nargs,
943 nargs=nargs,
937 const=const,
944 const=const,
938 default=default,
945 default=default,
939 type=type,
946 type=type,
940 choices=choices,
947 choices=choices,
941 required=required,
948 required=required,
942 help=help,
949 help=help,
943 metavar=metavar)
950 metavar=metavar)
944
951
945 def __call__(self, parser, namespace, values, option_string=None):
952 def __call__(self, parser, namespace, values, option_string=None):
946 items = _copy.copy(_ensure_value(namespace, self.dest, []))
953 items = _copy.copy(_ensure_value(namespace, self.dest, []))
947 items.append(values)
954 items.append(values)
948 setattr(namespace, self.dest, items)
955 setattr(namespace, self.dest, items)
949
956
950
957
951 class _AppendConstAction(Action):
958 class _AppendConstAction(Action):
952
959
953 def __init__(self,
960 def __init__(self,
954 option_strings,
961 option_strings,
955 dest,
962 dest,
956 const,
963 const,
957 default=None,
964 default=None,
958 required=False,
965 required=False,
959 help=None,
966 help=None,
960 metavar=None):
967 metavar=None):
961 super(_AppendConstAction, self).__init__(
968 super(_AppendConstAction, self).__init__(
962 option_strings=option_strings,
969 option_strings=option_strings,
963 dest=dest,
970 dest=dest,
964 nargs=0,
971 nargs=0,
965 const=const,
972 const=const,
966 default=default,
973 default=default,
967 required=required,
974 required=required,
968 help=help,
975 help=help,
969 metavar=metavar)
976 metavar=metavar)
970
977
971 def __call__(self, parser, namespace, values, option_string=None):
978 def __call__(self, parser, namespace, values, option_string=None):
972 items = _copy.copy(_ensure_value(namespace, self.dest, []))
979 items = _copy.copy(_ensure_value(namespace, self.dest, []))
973 items.append(self.const)
980 items.append(self.const)
974 setattr(namespace, self.dest, items)
981 setattr(namespace, self.dest, items)
975
982
976
983
977 class _CountAction(Action):
984 class _CountAction(Action):
978
985
979 def __init__(self,
986 def __init__(self,
980 option_strings,
987 option_strings,
981 dest,
988 dest,
982 default=None,
989 default=None,
983 required=False,
990 required=False,
984 help=None):
991 help=None):
985 super(_CountAction, self).__init__(
992 super(_CountAction, self).__init__(
986 option_strings=option_strings,
993 option_strings=option_strings,
987 dest=dest,
994 dest=dest,
988 nargs=0,
995 nargs=0,
989 default=default,
996 default=default,
990 required=required,
997 required=required,
991 help=help)
998 help=help)
992
999
993 def __call__(self, parser, namespace, values, option_string=None):
1000 def __call__(self, parser, namespace, values, option_string=None):
994 new_count = _ensure_value(namespace, self.dest, 0) + 1
1001 new_count = _ensure_value(namespace, self.dest, 0) + 1
995 setattr(namespace, self.dest, new_count)
1002 setattr(namespace, self.dest, new_count)
996
1003
997
1004
998 class _HelpAction(Action):
1005 class _HelpAction(Action):
999
1006
1000 def __init__(self,
1007 def __init__(self,
1001 option_strings,
1008 option_strings,
1002 dest=SUPPRESS,
1009 dest=SUPPRESS,
1003 default=SUPPRESS,
1010 default=SUPPRESS,
1004 help=None):
1011 help=None):
1005 super(_HelpAction, self).__init__(
1012 super(_HelpAction, self).__init__(
1006 option_strings=option_strings,
1013 option_strings=option_strings,
1007 dest=dest,
1014 dest=dest,
1008 default=default,
1015 default=default,
1009 nargs=0,
1016 nargs=0,
1010 help=help)
1017 help=help)
1011
1018
1012 def __call__(self, parser, namespace, values, option_string=None):
1019 def __call__(self, parser, namespace, values, option_string=None):
1013 parser.print_help()
1020 parser.print_help()
1014 parser.exit()
1021 parser.exit()
1015
1022
1016
1023
1017 class _VersionAction(Action):
1024 class _VersionAction(Action):
1018
1025
1019 def __init__(self,
1026 def __init__(self,
1020 option_strings,
1027 option_strings,
1028 version=None,
1021 dest=SUPPRESS,
1029 dest=SUPPRESS,
1022 default=SUPPRESS,
1030 default=SUPPRESS,
1023 help=None):
1031 help=None):
1024 super(_VersionAction, self).__init__(
1032 super(_VersionAction, self).__init__(
1025 option_strings=option_strings,
1033 option_strings=option_strings,
1026 dest=dest,
1034 dest=dest,
1027 default=default,
1035 default=default,
1028 nargs=0,
1036 nargs=0,
1029 help=help)
1037 help=help)
1038 self.version = version
1030
1039
1031 def __call__(self, parser, namespace, values, option_string=None):
1040 def __call__(self, parser, namespace, values, option_string=None):
1032 parser.print_version()
1041 version = self.version
1033 parser.exit()
1042 if version is None:
1043 version = parser.version
1044 formatter = parser._get_formatter()
1045 formatter.add_text(version)
1046 parser.exit(message=formatter.format_help())
1034
1047
1035
1048
1036 class _SubParsersAction(Action):
1049 class _SubParsersAction(Action):
1037
1050
1038 class _ChoicesPseudoAction(Action):
1051 class _ChoicesPseudoAction(Action):
1039
1052
1040 def __init__(self, name, help):
1053 def __init__(self, name, help):
1041 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
1054 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
1042 sup.__init__(option_strings=[], dest=name, help=help)
1055 sup.__init__(option_strings=[], dest=name, help=help)
1043
1056
1044 def __init__(self,
1057 def __init__(self,
1045 option_strings,
1058 option_strings,
1046 prog,
1059 prog,
1047 parser_class,
1060 parser_class,
1048 dest=SUPPRESS,
1061 dest=SUPPRESS,
1049 help=None,
1062 help=None,
1050 metavar=None):
1063 metavar=None):
1051
1064
1052 self._prog_prefix = prog
1065 self._prog_prefix = prog
1053 self._parser_class = parser_class
1066 self._parser_class = parser_class
1054 self._name_parser_map = {}
1067 self._name_parser_map = {}
1055 self._choices_actions = []
1068 self._choices_actions = []
1056
1069
1057 super(_SubParsersAction, self).__init__(
1070 super(_SubParsersAction, self).__init__(
1058 option_strings=option_strings,
1071 option_strings=option_strings,
1059 dest=dest,
1072 dest=dest,
1060 nargs=PARSER,
1073 nargs=PARSER,
1061 choices=self._name_parser_map,
1074 choices=self._name_parser_map,
1062 help=help,
1075 help=help,
1063 metavar=metavar)
1076 metavar=metavar)
1064
1077
1065 def add_parser(self, name, **kwargs):
1078 def add_parser(self, name, **kwargs):
1066 # set prog from the existing prefix
1079 # set prog from the existing prefix
1067 if kwargs.get('prog') is None:
1080 if kwargs.get('prog') is None:
1068 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1081 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1069
1082
1070 # create a pseudo-action to hold the choice help
1083 # create a pseudo-action to hold the choice help
1071 if 'help' in kwargs:
1084 if 'help' in kwargs:
1072 help = kwargs.pop('help')
1085 help = kwargs.pop('help')
1073 choice_action = self._ChoicesPseudoAction(name, help)
1086 choice_action = self._ChoicesPseudoAction(name, help)
1074 self._choices_actions.append(choice_action)
1087 self._choices_actions.append(choice_action)
1075
1088
1076 # create the parser and add it to the map
1089 # create the parser and add it to the map
1077 parser = self._parser_class(**kwargs)
1090 parser = self._parser_class(**kwargs)
1078 self._name_parser_map[name] = parser
1091 self._name_parser_map[name] = parser
1079 return parser
1092 return parser
1080
1093
1081 def _get_subactions(self):
1094 def _get_subactions(self):
1082 return self._choices_actions
1095 return self._choices_actions
1083
1096
1084 def __call__(self, parser, namespace, values, option_string=None):
1097 def __call__(self, parser, namespace, values, option_string=None):
1085 parser_name = values[0]
1098 parser_name = values[0]
1086 arg_strings = values[1:]
1099 arg_strings = values[1:]
1087
1100
1088 # set the parser name if requested
1101 # set the parser name if requested
1089 if self.dest is not SUPPRESS:
1102 if self.dest is not SUPPRESS:
1090 setattr(namespace, self.dest, parser_name)
1103 setattr(namespace, self.dest, parser_name)
1091
1104
1092 # select the parser
1105 # select the parser
1093 try:
1106 try:
1094 parser = self._name_parser_map[parser_name]
1107 parser = self._name_parser_map[parser_name]
1095 except KeyError:
1108 except KeyError:
1096 tup = parser_name, ', '.join(self._name_parser_map)
1109 tup = parser_name, ', '.join(self._name_parser_map)
1097 msg = _('unknown parser %r (choices: %s)' % tup)
1110 msg = _('unknown parser %r (choices: %s)' % tup)
1098 raise ArgumentError(self, msg)
1111 raise ArgumentError(self, msg)
1099
1112
1100 # parse all the remaining options into the namespace
1113 # parse all the remaining options into the namespace
1101 parser.parse_args(arg_strings, namespace)
1114 parser.parse_args(arg_strings, namespace)
1102
1115
1103
1116
1104 # ==============
1117 # ==============
1105 # Type classes
1118 # Type classes
1106 # ==============
1119 # ==============
1107
1120
1108 class FileType(object):
1121 class FileType(object):
1109 """Factory for creating file object types
1122 """Factory for creating file object types
1110
1123
1111 Instances of FileType are typically passed as type= arguments to the
1124 Instances of FileType are typically passed as type= arguments to the
1112 ArgumentParser add_argument() method.
1125 ArgumentParser add_argument() method.
1113
1126
1114 Keyword Arguments:
1127 Keyword Arguments:
1115 - mode -- A string indicating how the file is to be opened. Accepts the
1128 - mode -- A string indicating how the file is to be opened. Accepts the
1116 same values as the builtin open() function.
1129 same values as the builtin open() function.
1117 - bufsize -- The file's desired buffer size. Accepts the same values as
1130 - bufsize -- The file's desired buffer size. Accepts the same values as
1118 the builtin open() function.
1131 the builtin open() function.
1119 """
1132 """
1120
1133
1121 def __init__(self, mode='r', bufsize=None):
1134 def __init__(self, mode='r', bufsize=None):
1122 self._mode = mode
1135 self._mode = mode
1123 self._bufsize = bufsize
1136 self._bufsize = bufsize
1124
1137
1125 def __call__(self, string):
1138 def __call__(self, string):
1126 # the special argument "-" means sys.std{in,out}
1139 # the special argument "-" means sys.std{in,out}
1127 if string == '-':
1140 if string == '-':
1128 if 'r' in self._mode:
1141 if 'r' in self._mode:
1129 return _sys.stdin
1142 return _sys.stdin
1130 elif 'w' in self._mode:
1143 elif 'w' in self._mode:
1131 return _sys.stdout
1144 return _sys.stdout
1132 else:
1145 else:
1133 msg = _('argument "-" with mode %r' % self._mode)
1146 msg = _('argument "-" with mode %r' % self._mode)
1134 raise ValueError(msg)
1147 raise ValueError(msg)
1135
1148
1136 # all other arguments are used as file names
1149 # all other arguments are used as file names
1137 if self._bufsize:
1150 if self._bufsize:
1138 return open(string, self._mode, self._bufsize)
1151 return open(string, self._mode, self._bufsize)
1139 else:
1152 else:
1140 return open(string, self._mode)
1153 return open(string, self._mode)
1141
1154
1142 def __repr__(self):
1155 def __repr__(self):
1143 args = [self._mode, self._bufsize]
1156 args = [self._mode, self._bufsize]
1144 args_str = ', '.join([repr(arg) for arg in args if arg is not None])
1157 args_str = ', '.join([repr(arg) for arg in args if arg is not None])
1145 return '%s(%s)' % (type(self).__name__, args_str)
1158 return '%s(%s)' % (type(self).__name__, args_str)
1146
1159
1147 # ===========================
1160 # ===========================
1148 # Optional and Positional Parsing
1161 # Optional and Positional Parsing
1149 # ===========================
1162 # ===========================
1150
1163
1151 class Namespace(_AttributeHolder):
1164 class Namespace(_AttributeHolder):
1152 """Simple object for storing attributes.
1165 """Simple object for storing attributes.
1153
1166
1154 Implements equality by attribute names and values, and provides a simple
1167 Implements equality by attribute names and values, and provides a simple
1155 string representation.
1168 string representation.
1156 """
1169 """
1157
1170
1158 def __init__(self, **kwargs):
1171 def __init__(self, **kwargs):
1159 for name in kwargs:
1172 for name in kwargs:
1160 setattr(self, name, kwargs[name])
1173 setattr(self, name, kwargs[name])
1161
1174
1162 def __eq__(self, other):
1175 def __eq__(self, other):
1163 return vars(self) == vars(other)
1176 return vars(self) == vars(other)
1164
1177
1165 def __ne__(self, other):
1178 def __ne__(self, other):
1166 return not (self == other)
1179 return not (self == other)
1167
1180
1168
1181
1169 class _ActionsContainer(object):
1182 class _ActionsContainer(object):
1170
1183
1171 def __init__(self,
1184 def __init__(self,
1172 description,
1185 description,
1173 prefix_chars,
1186 prefix_chars,
1174 argument_default,
1187 argument_default,
1175 conflict_handler):
1188 conflict_handler):
1176 super(_ActionsContainer, self).__init__()
1189 super(_ActionsContainer, self).__init__()
1177
1190
1178 self.description = description
1191 self.description = description
1179 self.argument_default = argument_default
1192 self.argument_default = argument_default
1180 self.prefix_chars = prefix_chars
1193 self.prefix_chars = prefix_chars
1181 self.conflict_handler = conflict_handler
1194 self.conflict_handler = conflict_handler
1182
1195
1183 # set up registries
1196 # set up registries
1184 self._registries = {}
1197 self._registries = {}
1185
1198
1186 # register actions
1199 # register actions
1187 self.register('action', None, _StoreAction)
1200 self.register('action', None, _StoreAction)
1188 self.register('action', 'store', _StoreAction)
1201 self.register('action', 'store', _StoreAction)
1189 self.register('action', 'store_const', _StoreConstAction)
1202 self.register('action', 'store_const', _StoreConstAction)
1190 self.register('action', 'store_true', _StoreTrueAction)
1203 self.register('action', 'store_true', _StoreTrueAction)
1191 self.register('action', 'store_false', _StoreFalseAction)
1204 self.register('action', 'store_false', _StoreFalseAction)
1192 self.register('action', 'append', _AppendAction)
1205 self.register('action', 'append', _AppendAction)
1193 self.register('action', 'append_const', _AppendConstAction)
1206 self.register('action', 'append_const', _AppendConstAction)
1194 self.register('action', 'count', _CountAction)
1207 self.register('action', 'count', _CountAction)
1195 self.register('action', 'help', _HelpAction)
1208 self.register('action', 'help', _HelpAction)
1196 self.register('action', 'version', _VersionAction)
1209 self.register('action', 'version', _VersionAction)
1197 self.register('action', 'parsers', _SubParsersAction)
1210 self.register('action', 'parsers', _SubParsersAction)
1198
1211
1199 # raise an exception if the conflict handler is invalid
1212 # raise an exception if the conflict handler is invalid
1200 self._get_handler()
1213 self._get_handler()
1201
1214
1202 # action storage
1215 # action storage
1203 self._actions = []
1216 self._actions = []
1204 self._option_string_actions = {}
1217 self._option_string_actions = {}
1205
1218
1206 # groups
1219 # groups
1207 self._action_groups = []
1220 self._action_groups = []
1208 self._mutually_exclusive_groups = []
1221 self._mutually_exclusive_groups = []
1209
1222
1210 # defaults storage
1223 # defaults storage
1211 self._defaults = {}
1224 self._defaults = {}
1212
1225
1213 # determines whether an "option" looks like a negative number
1226 # determines whether an "option" looks like a negative number
1214 self._negative_number_matcher = _re.compile(r'^-\d+|-\d*.\d+$')
1227 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1215
1228
1216 # whether or not there are any optionals that look like negative
1229 # whether or not there are any optionals that look like negative
1217 # numbers -- uses a list so it can be shared and edited
1230 # numbers -- uses a list so it can be shared and edited
1218 self._has_negative_number_optionals = []
1231 self._has_negative_number_optionals = []
1219
1232
1220 # ====================
1233 # ====================
1221 # Registration methods
1234 # Registration methods
1222 # ====================
1235 # ====================
1223 def register(self, registry_name, value, object):
1236 def register(self, registry_name, value, object):
1224 registry = self._registries.setdefault(registry_name, {})
1237 registry = self._registries.setdefault(registry_name, {})
1225 registry[value] = object
1238 registry[value] = object
1226
1239
1227 def _registry_get(self, registry_name, value, default=None):
1240 def _registry_get(self, registry_name, value, default=None):
1228 return self._registries[registry_name].get(value, default)
1241 return self._registries[registry_name].get(value, default)
1229
1242
1230 # ==================================
1243 # ==================================
1231 # Namespace default settings methods
1244 # Namespace default accessor methods
1232 # ==================================
1245 # ==================================
1233 def set_defaults(self, **kwargs):
1246 def set_defaults(self, **kwargs):
1234 self._defaults.update(kwargs)
1247 self._defaults.update(kwargs)
1235
1248
1236 # if these defaults match any existing arguments, replace
1249 # if these defaults match any existing arguments, replace
1237 # the previous default on the object with the new one
1250 # the previous default on the object with the new one
1238 for action in self._actions:
1251 for action in self._actions:
1239 if action.dest in kwargs:
1252 if action.dest in kwargs:
1240 action.default = kwargs[action.dest]
1253 action.default = kwargs[action.dest]
1241
1254
1255 def get_default(self, dest):
1256 for action in self._actions:
1257 if action.dest == dest and action.default is not None:
1258 return action.default
1259 return self._defaults.get(dest, None)
1260
1261
1242 # =======================
1262 # =======================
1243 # Adding argument actions
1263 # Adding argument actions
1244 # =======================
1264 # =======================
1245 def add_argument(self, *args, **kwargs):
1265 def add_argument(self, *args, **kwargs):
1246 """
1266 """
1247 add_argument(dest, ..., name=value, ...)
1267 add_argument(dest, ..., name=value, ...)
1248 add_argument(option_string, option_string, ..., name=value, ...)
1268 add_argument(option_string, option_string, ..., name=value, ...)
1249 """
1269 """
1250
1270
1251 # if no positional args are supplied or only one is supplied and
1271 # if no positional args are supplied or only one is supplied and
1252 # it doesn't look like an option string, parse a positional
1272 # it doesn't look like an option string, parse a positional
1253 # argument
1273 # argument
1254 chars = self.prefix_chars
1274 chars = self.prefix_chars
1255 if not args or len(args) == 1 and args[0][0] not in chars:
1275 if not args or len(args) == 1 and args[0][0] not in chars:
1276 if args and 'dest' in kwargs:
1277 raise ValueError('dest supplied twice for positional argument')
1256 kwargs = self._get_positional_kwargs(*args, **kwargs)
1278 kwargs = self._get_positional_kwargs(*args, **kwargs)
1257
1279
1258 # otherwise, we're adding an optional argument
1280 # otherwise, we're adding an optional argument
1259 else:
1281 else:
1260 kwargs = self._get_optional_kwargs(*args, **kwargs)
1282 kwargs = self._get_optional_kwargs(*args, **kwargs)
1261
1283
1262 # if no default was supplied, use the parser-level default
1284 # if no default was supplied, use the parser-level default
1263 if 'default' not in kwargs:
1285 if 'default' not in kwargs:
1264 dest = kwargs['dest']
1286 dest = kwargs['dest']
1265 if dest in self._defaults:
1287 if dest in self._defaults:
1266 kwargs['default'] = self._defaults[dest]
1288 kwargs['default'] = self._defaults[dest]
1267 elif self.argument_default is not None:
1289 elif self.argument_default is not None:
1268 kwargs['default'] = self.argument_default
1290 kwargs['default'] = self.argument_default
1269
1291
1270 # create the action object, and add it to the parser
1292 # create the action object, and add it to the parser
1271 action_class = self._pop_action_class(kwargs)
1293 action_class = self._pop_action_class(kwargs)
1294 if not _callable(action_class):
1295 raise ValueError('unknown action "%s"' % action_class)
1272 action = action_class(**kwargs)
1296 action = action_class(**kwargs)
1273 return self._add_action(action)
1297 return self._add_action(action)
1274
1298
1275 def add_argument_group(self, *args, **kwargs):
1299 def add_argument_group(self, *args, **kwargs):
1276 group = _ArgumentGroup(self, *args, **kwargs)
1300 group = _ArgumentGroup(self, *args, **kwargs)
1277 self._action_groups.append(group)
1301 self._action_groups.append(group)
1278 return group
1302 return group
1279
1303
1280 def add_mutually_exclusive_group(self, **kwargs):
1304 def add_mutually_exclusive_group(self, **kwargs):
1281 group = _MutuallyExclusiveGroup(self, **kwargs)
1305 group = _MutuallyExclusiveGroup(self, **kwargs)
1282 self._mutually_exclusive_groups.append(group)
1306 self._mutually_exclusive_groups.append(group)
1283 return group
1307 return group
1284
1308
1285 def _add_action(self, action):
1309 def _add_action(self, action):
1286 # resolve any conflicts
1310 # resolve any conflicts
1287 self._check_conflict(action)
1311 self._check_conflict(action)
1288
1312
1289 # add to actions list
1313 # add to actions list
1290 self._actions.append(action)
1314 self._actions.append(action)
1291 action.container = self
1315 action.container = self
1292
1316
1293 # index the action by any option strings it has
1317 # index the action by any option strings it has
1294 for option_string in action.option_strings:
1318 for option_string in action.option_strings:
1295 self._option_string_actions[option_string] = action
1319 self._option_string_actions[option_string] = action
1296
1320
1297 # set the flag if any option strings look like negative numbers
1321 # set the flag if any option strings look like negative numbers
1298 for option_string in action.option_strings:
1322 for option_string in action.option_strings:
1299 if self._negative_number_matcher.match(option_string):
1323 if self._negative_number_matcher.match(option_string):
1300 if not self._has_negative_number_optionals:
1324 if not self._has_negative_number_optionals:
1301 self._has_negative_number_optionals.append(True)
1325 self._has_negative_number_optionals.append(True)
1302
1326
1303 # return the created action
1327 # return the created action
1304 return action
1328 return action
1305
1329
1306 def _remove_action(self, action):
1330 def _remove_action(self, action):
1307 self._actions.remove(action)
1331 self._actions.remove(action)
1308
1332
1309 def _add_container_actions(self, container):
1333 def _add_container_actions(self, container):
1310 # collect groups by titles
1334 # collect groups by titles
1311 title_group_map = {}
1335 title_group_map = {}
1312 for group in self._action_groups:
1336 for group in self._action_groups:
1313 if group.title in title_group_map:
1337 if group.title in title_group_map:
1314 msg = _('cannot merge actions - two groups are named %r')
1338 msg = _('cannot merge actions - two groups are named %r')
1315 raise ValueError(msg % (group.title))
1339 raise ValueError(msg % (group.title))
1316 title_group_map[group.title] = group
1340 title_group_map[group.title] = group
1317
1341
1318 # map each action to its group
1342 # map each action to its group
1319 group_map = {}
1343 group_map = {}
1320 for group in container._action_groups:
1344 for group in container._action_groups:
1321
1345
1322 # if a group with the title exists, use that, otherwise
1346 # if a group with the title exists, use that, otherwise
1323 # create a new group matching the container's group
1347 # create a new group matching the container's group
1324 if group.title not in title_group_map:
1348 if group.title not in title_group_map:
1325 title_group_map[group.title] = self.add_argument_group(
1349 title_group_map[group.title] = self.add_argument_group(
1326 title=group.title,
1350 title=group.title,
1327 description=group.description,
1351 description=group.description,
1328 conflict_handler=group.conflict_handler)
1352 conflict_handler=group.conflict_handler)
1329
1353
1330 # map the actions to their new group
1354 # map the actions to their new group
1331 for action in group._group_actions:
1355 for action in group._group_actions:
1332 group_map[action] = title_group_map[group.title]
1356 group_map[action] = title_group_map[group.title]
1333
1357
1334 # add container's mutually exclusive groups
1358 # add container's mutually exclusive groups
1335 # NOTE: if add_mutually_exclusive_group ever gains title= and
1359 # NOTE: if add_mutually_exclusive_group ever gains title= and
1336 # description= then this code will need to be expanded as above
1360 # description= then this code will need to be expanded as above
1337 for group in container._mutually_exclusive_groups:
1361 for group in container._mutually_exclusive_groups:
1338 mutex_group = self.add_mutually_exclusive_group(
1362 mutex_group = self.add_mutually_exclusive_group(
1339 required=group.required)
1363 required=group.required)
1340
1364
1341 # map the actions to their new mutex group
1365 # map the actions to their new mutex group
1342 for action in group._group_actions:
1366 for action in group._group_actions:
1343 group_map[action] = mutex_group
1367 group_map[action] = mutex_group
1344
1368
1345 # add all actions to this container or their group
1369 # add all actions to this container or their group
1346 for action in container._actions:
1370 for action in container._actions:
1347 group_map.get(action, self)._add_action(action)
1371 group_map.get(action, self)._add_action(action)
1348
1372
1349 def _get_positional_kwargs(self, dest, **kwargs):
1373 def _get_positional_kwargs(self, dest, **kwargs):
1350 # make sure required is not specified
1374 # make sure required is not specified
1351 if 'required' in kwargs:
1375 if 'required' in kwargs:
1352 msg = _("'required' is an invalid argument for positionals")
1376 msg = _("'required' is an invalid argument for positionals")
1353 raise TypeError(msg)
1377 raise TypeError(msg)
1354
1378
1355 # mark positional arguments as required if at least one is
1379 # mark positional arguments as required if at least one is
1356 # always required
1380 # always required
1357 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1381 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1358 kwargs['required'] = True
1382 kwargs['required'] = True
1359 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1383 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1360 kwargs['required'] = True
1384 kwargs['required'] = True
1361
1385
1362 # return the keyword arguments with no option strings
1386 # return the keyword arguments with no option strings
1363 return dict(kwargs, dest=dest, option_strings=[])
1387 return dict(kwargs, dest=dest, option_strings=[])
1364
1388
1365 def _get_optional_kwargs(self, *args, **kwargs):
1389 def _get_optional_kwargs(self, *args, **kwargs):
1366 # determine short and long option strings
1390 # determine short and long option strings
1367 option_strings = []
1391 option_strings = []
1368 long_option_strings = []
1392 long_option_strings = []
1369 for option_string in args:
1393 for option_string in args:
1370 # error on one-or-fewer-character option strings
1394 # error on one-or-fewer-character option strings
1371 if len(option_string) < 2:
1395 if len(option_string) < 2:
1372 msg = _('invalid option string %r: '
1396 msg = _('invalid option string %r: '
1373 'must be at least two characters long')
1397 'must be at least two characters long')
1374 raise ValueError(msg % option_string)
1398 raise ValueError(msg % option_string)
1375
1399
1376 # error on strings that don't start with an appropriate prefix
1400 # error on strings that don't start with an appropriate prefix
1377 if not option_string[0] in self.prefix_chars:
1401 if not option_string[0] in self.prefix_chars:
1378 msg = _('invalid option string %r: '
1402 msg = _('invalid option string %r: '
1379 'must start with a character %r')
1403 'must start with a character %r')
1380 tup = option_string, self.prefix_chars
1404 tup = option_string, self.prefix_chars
1381 raise ValueError(msg % tup)
1405 raise ValueError(msg % tup)
1382
1406
1383 # error on strings that are all prefix characters
1407 # error on strings that are all prefix characters
1384 if not (_set(option_string) - _set(self.prefix_chars)):
1408 if not (_set(option_string) - _set(self.prefix_chars)):
1385 msg = _('invalid option string %r: '
1409 msg = _('invalid option string %r: '
1386 'must contain characters other than %r')
1410 'must contain characters other than %r')
1387 tup = option_string, self.prefix_chars
1411 tup = option_string, self.prefix_chars
1388 raise ValueError(msg % tup)
1412 raise ValueError(msg % tup)
1389
1413
1390 # strings starting with two prefix characters are long options
1414 # strings starting with two prefix characters are long options
1391 option_strings.append(option_string)
1415 option_strings.append(option_string)
1392 if option_string[0] in self.prefix_chars:
1416 if option_string[0] in self.prefix_chars:
1393 if option_string[1] in self.prefix_chars:
1417 if option_string[1] in self.prefix_chars:
1394 long_option_strings.append(option_string)
1418 long_option_strings.append(option_string)
1395
1419
1396 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1420 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1397 dest = kwargs.pop('dest', None)
1421 dest = kwargs.pop('dest', None)
1398 if dest is None:
1422 if dest is None:
1399 if long_option_strings:
1423 if long_option_strings:
1400 dest_option_string = long_option_strings[0]
1424 dest_option_string = long_option_strings[0]
1401 else:
1425 else:
1402 dest_option_string = option_strings[0]
1426 dest_option_string = option_strings[0]
1403 dest = dest_option_string.lstrip(self.prefix_chars)
1427 dest = dest_option_string.lstrip(self.prefix_chars)
1404 dest = dest.replace('-', '_')
1428 dest = dest.replace('-', '_')
1405
1429
1406 # return the updated keyword arguments
1430 # return the updated keyword arguments
1407 return dict(kwargs, dest=dest, option_strings=option_strings)
1431 return dict(kwargs, dest=dest, option_strings=option_strings)
1408
1432
1409 def _pop_action_class(self, kwargs, default=None):
1433 def _pop_action_class(self, kwargs, default=None):
1410 action = kwargs.pop('action', default)
1434 action = kwargs.pop('action', default)
1411 return self._registry_get('action', action, action)
1435 return self._registry_get('action', action, action)
1412
1436
1413 def _get_handler(self):
1437 def _get_handler(self):
1414 # determine function from conflict handler string
1438 # determine function from conflict handler string
1415 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1439 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1416 try:
1440 try:
1417 return getattr(self, handler_func_name)
1441 return getattr(self, handler_func_name)
1418 except AttributeError:
1442 except AttributeError:
1419 msg = _('invalid conflict_resolution value: %r')
1443 msg = _('invalid conflict_resolution value: %r')
1420 raise ValueError(msg % self.conflict_handler)
1444 raise ValueError(msg % self.conflict_handler)
1421
1445
1422 def _check_conflict(self, action):
1446 def _check_conflict(self, action):
1423
1447
1424 # find all options that conflict with this option
1448 # find all options that conflict with this option
1425 confl_optionals = []
1449 confl_optionals = []
1426 for option_string in action.option_strings:
1450 for option_string in action.option_strings:
1427 if option_string in self._option_string_actions:
1451 if option_string in self._option_string_actions:
1428 confl_optional = self._option_string_actions[option_string]
1452 confl_optional = self._option_string_actions[option_string]
1429 confl_optionals.append((option_string, confl_optional))
1453 confl_optionals.append((option_string, confl_optional))
1430
1454
1431 # resolve any conflicts
1455 # resolve any conflicts
1432 if confl_optionals:
1456 if confl_optionals:
1433 conflict_handler = self._get_handler()
1457 conflict_handler = self._get_handler()
1434 conflict_handler(action, confl_optionals)
1458 conflict_handler(action, confl_optionals)
1435
1459
1436 def _handle_conflict_error(self, action, conflicting_actions):
1460 def _handle_conflict_error(self, action, conflicting_actions):
1437 message = _('conflicting option string(s): %s')
1461 message = _('conflicting option string(s): %s')
1438 conflict_string = ', '.join([option_string
1462 conflict_string = ', '.join([option_string
1439 for option_string, action
1463 for option_string, action
1440 in conflicting_actions])
1464 in conflicting_actions])
1441 raise ArgumentError(action, message % conflict_string)
1465 raise ArgumentError(action, message % conflict_string)
1442
1466
1443 def _handle_conflict_resolve(self, action, conflicting_actions):
1467 def _handle_conflict_resolve(self, action, conflicting_actions):
1444
1468
1445 # remove all conflicting options
1469 # remove all conflicting options
1446 for option_string, action in conflicting_actions:
1470 for option_string, action in conflicting_actions:
1447
1471
1448 # remove the conflicting option
1472 # remove the conflicting option
1449 action.option_strings.remove(option_string)
1473 action.option_strings.remove(option_string)
1450 self._option_string_actions.pop(option_string, None)
1474 self._option_string_actions.pop(option_string, None)
1451
1475
1452 # if the option now has no option string, remove it from the
1476 # if the option now has no option string, remove it from the
1453 # container holding it
1477 # container holding it
1454 if not action.option_strings:
1478 if not action.option_strings:
1455 action.container._remove_action(action)
1479 action.container._remove_action(action)
1456
1480
1457
1481
1458 class _ArgumentGroup(_ActionsContainer):
1482 class _ArgumentGroup(_ActionsContainer):
1459
1483
1460 def __init__(self, container, title=None, description=None, **kwargs):
1484 def __init__(self, container, title=None, description=None, **kwargs):
1461 # add any missing keyword arguments by checking the container
1485 # add any missing keyword arguments by checking the container
1462 update = kwargs.setdefault
1486 update = kwargs.setdefault
1463 update('conflict_handler', container.conflict_handler)
1487 update('conflict_handler', container.conflict_handler)
1464 update('prefix_chars', container.prefix_chars)
1488 update('prefix_chars', container.prefix_chars)
1465 update('argument_default', container.argument_default)
1489 update('argument_default', container.argument_default)
1466 super_init = super(_ArgumentGroup, self).__init__
1490 super_init = super(_ArgumentGroup, self).__init__
1467 super_init(description=description, **kwargs)
1491 super_init(description=description, **kwargs)
1468
1492
1469 # group attributes
1493 # group attributes
1470 self.title = title
1494 self.title = title
1471 self._group_actions = []
1495 self._group_actions = []
1472
1496
1473 # share most attributes with the container
1497 # share most attributes with the container
1474 self._registries = container._registries
1498 self._registries = container._registries
1475 self._actions = container._actions
1499 self._actions = container._actions
1476 self._option_string_actions = container._option_string_actions
1500 self._option_string_actions = container._option_string_actions
1477 self._defaults = container._defaults
1501 self._defaults = container._defaults
1478 self._has_negative_number_optionals = \
1502 self._has_negative_number_optionals = \
1479 container._has_negative_number_optionals
1503 container._has_negative_number_optionals
1480
1504
1481 def _add_action(self, action):
1505 def _add_action(self, action):
1482 action = super(_ArgumentGroup, self)._add_action(action)
1506 action = super(_ArgumentGroup, self)._add_action(action)
1483 self._group_actions.append(action)
1507 self._group_actions.append(action)
1484 return action
1508 return action
1485
1509
1486 def _remove_action(self, action):
1510 def _remove_action(self, action):
1487 super(_ArgumentGroup, self)._remove_action(action)
1511 super(_ArgumentGroup, self)._remove_action(action)
1488 self._group_actions.remove(action)
1512 self._group_actions.remove(action)
1489
1513
1490
1514
1491 class _MutuallyExclusiveGroup(_ArgumentGroup):
1515 class _MutuallyExclusiveGroup(_ArgumentGroup):
1492
1516
1493 def __init__(self, container, required=False):
1517 def __init__(self, container, required=False):
1494 super(_MutuallyExclusiveGroup, self).__init__(container)
1518 super(_MutuallyExclusiveGroup, self).__init__(container)
1495 self.required = required
1519 self.required = required
1496 self._container = container
1520 self._container = container
1497
1521
1498 def _add_action(self, action):
1522 def _add_action(self, action):
1499 if action.required:
1523 if action.required:
1500 msg = _('mutually exclusive arguments must be optional')
1524 msg = _('mutually exclusive arguments must be optional')
1501 raise ValueError(msg)
1525 raise ValueError(msg)
1502 action = self._container._add_action(action)
1526 action = self._container._add_action(action)
1503 self._group_actions.append(action)
1527 self._group_actions.append(action)
1504 return action
1528 return action
1505
1529
1506 def _remove_action(self, action):
1530 def _remove_action(self, action):
1507 self._container._remove_action(action)
1531 self._container._remove_action(action)
1508 self._group_actions.remove(action)
1532 self._group_actions.remove(action)
1509
1533
1510
1534
1511 class ArgumentParser(_AttributeHolder, _ActionsContainer):
1535 class ArgumentParser(_AttributeHolder, _ActionsContainer):
1512 """Object for parsing command line strings into Python objects.
1536 """Object for parsing command line strings into Python objects.
1513
1537
1514 Keyword Arguments:
1538 Keyword Arguments:
1515 - prog -- The name of the program (default: sys.argv[0])
1539 - prog -- The name of the program (default: sys.argv[0])
1516 - usage -- A usage message (default: auto-generated from arguments)
1540 - usage -- A usage message (default: auto-generated from arguments)
1517 - description -- A description of what the program does
1541 - description -- A description of what the program does
1518 - epilog -- Text following the argument descriptions
1542 - epilog -- Text following the argument descriptions
1519 - version -- Add a -v/--version option with the given version string
1543 - version -- Add a -v/--version option with the given version string
1520 - parents -- Parsers whose arguments should be copied into this one
1544 - parents -- Parsers whose arguments should be copied into this one
1521 - formatter_class -- HelpFormatter class for printing help messages
1545 - formatter_class -- HelpFormatter class for printing help messages
1522 - prefix_chars -- Characters that prefix optional arguments
1546 - prefix_chars -- Characters that prefix optional arguments
1523 - fromfile_prefix_chars -- Characters that prefix files containing
1547 - fromfile_prefix_chars -- Characters that prefix files containing
1524 additional arguments
1548 additional arguments
1525 - argument_default -- The default value for all arguments
1549 - argument_default -- The default value for all arguments
1526 - conflict_handler -- String indicating how to handle conflicts
1550 - conflict_handler -- String indicating how to handle conflicts
1527 - add_help -- Add a -h/-help option
1551 - add_help -- Add a -h/-help option
1528 """
1552 """
1529
1553
1530 def __init__(self,
1554 def __init__(self,
1531 prog=None,
1555 prog=None,
1532 usage=None,
1556 usage=None,
1533 description=None,
1557 description=None,
1534 epilog=None,
1558 epilog=None,
1535 version=None,
1559 version=None,
1536 parents=[],
1560 parents=[],
1537 formatter_class=HelpFormatter,
1561 formatter_class=HelpFormatter,
1538 prefix_chars='-',
1562 prefix_chars='-',
1539 fromfile_prefix_chars=None,
1563 fromfile_prefix_chars=None,
1540 argument_default=None,
1564 argument_default=None,
1541 conflict_handler='error',
1565 conflict_handler='error',
1542 add_help=True):
1566 add_help=True):
1543
1567
1544 superinit = super(ArgumentParser, self).__init__
1568 superinit = super(ArgumentParser, self).__init__
1545 superinit(description=description,
1569 superinit(description=description,
1546 prefix_chars=prefix_chars,
1570 prefix_chars=prefix_chars,
1547 argument_default=argument_default,
1571 argument_default=argument_default,
1548 conflict_handler=conflict_handler)
1572 conflict_handler=conflict_handler)
1549
1573
1550 # default setting for prog
1574 # default setting for prog
1551 if prog is None:
1575 if prog is None:
1552 prog = _os.path.basename(_sys.argv[0])
1576 prog = _os.path.basename(_sys.argv[0])
1553
1577
1554 self.prog = prog
1578 self.prog = prog
1555 self.usage = usage
1579 self.usage = usage
1556 self.epilog = epilog
1580 self.epilog = epilog
1557 self.version = version
1581 self.version = version
1558 self.formatter_class = formatter_class
1582 self.formatter_class = formatter_class
1559 self.fromfile_prefix_chars = fromfile_prefix_chars
1583 self.fromfile_prefix_chars = fromfile_prefix_chars
1560 self.add_help = add_help
1584 self.add_help = add_help
1561
1585
1562 add_group = self.add_argument_group
1586 add_group = self.add_argument_group
1563 self._positionals = add_group(_('positional arguments'))
1587 self._positionals = add_group(_('positional arguments'))
1564 self._optionals = add_group(_('optional arguments'))
1588 self._optionals = add_group(_('optional arguments'))
1565 self._subparsers = None
1589 self._subparsers = None
1566
1590
1567 # register types
1591 # register types
1568 def identity(string):
1592 def identity(string):
1569 return string
1593 return string
1570 self.register('type', None, identity)
1594 self.register('type', None, identity)
1571
1595
1572 # add help and version arguments if necessary
1596 # add help and version arguments if necessary
1573 # (using explicit default to override global argument_default)
1597 # (using explicit default to override global argument_default)
1574 if self.add_help:
1598 if self.add_help:
1575 self.add_argument(
1599 self.add_argument(
1576 '-h', '--help', action='help', default=SUPPRESS,
1600 '-h', '--help', action='help', default=SUPPRESS,
1577 help=_('show this help message and exit'))
1601 help=_('show this help message and exit'))
1578 if self.version:
1602 if self.version:
1579 self.add_argument(
1603 self.add_argument(
1580 '-v', '--version', action='version', default=SUPPRESS,
1604 '-v', '--version', action='version', default=SUPPRESS,
1605 version=self.version,
1581 help=_("show program's version number and exit"))
1606 help=_("show program's version number and exit"))
1582
1607
1583 # add parent arguments and defaults
1608 # add parent arguments and defaults
1584 for parent in parents:
1609 for parent in parents:
1585 self._add_container_actions(parent)
1610 self._add_container_actions(parent)
1586 try:
1611 try:
1587 defaults = parent._defaults
1612 defaults = parent._defaults
1588 except AttributeError:
1613 except AttributeError:
1589 pass
1614 pass
1590 else:
1615 else:
1591 self._defaults.update(defaults)
1616 self._defaults.update(defaults)
1592
1617
1593 # =======================
1618 # =======================
1594 # Pretty __repr__ methods
1619 # Pretty __repr__ methods
1595 # =======================
1620 # =======================
1596 def _get_kwargs(self):
1621 def _get_kwargs(self):
1597 names = [
1622 names = [
1598 'prog',
1623 'prog',
1599 'usage',
1624 'usage',
1600 'description',
1625 'description',
1601 'version',
1626 'version',
1602 'formatter_class',
1627 'formatter_class',
1603 'conflict_handler',
1628 'conflict_handler',
1604 'add_help',
1629 'add_help',
1605 ]
1630 ]
1606 return [(name, getattr(self, name)) for name in names]
1631 return [(name, getattr(self, name)) for name in names]
1607
1632
1608 # ==================================
1633 # ==================================
1609 # Optional/Positional adding methods
1634 # Optional/Positional adding methods
1610 # ==================================
1635 # ==================================
1611 def add_subparsers(self, **kwargs):
1636 def add_subparsers(self, **kwargs):
1612 if self._subparsers is not None:
1637 if self._subparsers is not None:
1613 self.error(_('cannot have multiple subparser arguments'))
1638 self.error(_('cannot have multiple subparser arguments'))
1614
1639
1615 # add the parser class to the arguments if it's not present
1640 # add the parser class to the arguments if it's not present
1616 kwargs.setdefault('parser_class', type(self))
1641 kwargs.setdefault('parser_class', type(self))
1617
1642
1618 if 'title' in kwargs or 'description' in kwargs:
1643 if 'title' in kwargs or 'description' in kwargs:
1619 title = _(kwargs.pop('title', 'subcommands'))
1644 title = _(kwargs.pop('title', 'subcommands'))
1620 description = _(kwargs.pop('description', None))
1645 description = _(kwargs.pop('description', None))
1621 self._subparsers = self.add_argument_group(title, description)
1646 self._subparsers = self.add_argument_group(title, description)
1622 else:
1647 else:
1623 self._subparsers = self._positionals
1648 self._subparsers = self._positionals
1624
1649
1625 # prog defaults to the usage message of this parser, skipping
1650 # prog defaults to the usage message of this parser, skipping
1626 # optional arguments and with no "usage:" prefix
1651 # optional arguments and with no "usage:" prefix
1627 if kwargs.get('prog') is None:
1652 if kwargs.get('prog') is None:
1628 formatter = self._get_formatter()
1653 formatter = self._get_formatter()
1629 positionals = self._get_positional_actions()
1654 positionals = self._get_positional_actions()
1630 groups = self._mutually_exclusive_groups
1655 groups = self._mutually_exclusive_groups
1631 formatter.add_usage(self.usage, positionals, groups, '')
1656 formatter.add_usage(self.usage, positionals, groups, '')
1632 kwargs['prog'] = formatter.format_help().strip()
1657 kwargs['prog'] = formatter.format_help().strip()
1633
1658
1634 # create the parsers action and add it to the positionals list
1659 # create the parsers action and add it to the positionals list
1635 parsers_class = self._pop_action_class(kwargs, 'parsers')
1660 parsers_class = self._pop_action_class(kwargs, 'parsers')
1636 action = parsers_class(option_strings=[], **kwargs)
1661 action = parsers_class(option_strings=[], **kwargs)
1637 self._subparsers._add_action(action)
1662 self._subparsers._add_action(action)
1638
1663
1639 # return the created parsers action
1664 # return the created parsers action
1640 return action
1665 return action
1641
1666
1642 def _add_action(self, action):
1667 def _add_action(self, action):
1643 if action.option_strings:
1668 if action.option_strings:
1644 self._optionals._add_action(action)
1669 self._optionals._add_action(action)
1645 else:
1670 else:
1646 self._positionals._add_action(action)
1671 self._positionals._add_action(action)
1647 return action
1672 return action
1648
1673
1649 def _get_optional_actions(self):
1674 def _get_optional_actions(self):
1650 return [action
1675 return [action
1651 for action in self._actions
1676 for action in self._actions
1652 if action.option_strings]
1677 if action.option_strings]
1653
1678
1654 def _get_positional_actions(self):
1679 def _get_positional_actions(self):
1655 return [action
1680 return [action
1656 for action in self._actions
1681 for action in self._actions
1657 if not action.option_strings]
1682 if not action.option_strings]
1658
1683
1659 # =====================================
1684 # =====================================
1660 # Command line argument parsing methods
1685 # Command line argument parsing methods
1661 # =====================================
1686 # =====================================
1662 def parse_args(self, args=None, namespace=None):
1687 def parse_args(self, args=None, namespace=None):
1663 args, argv = self.parse_known_args(args, namespace)
1688 args, argv = self.parse_known_args(args, namespace)
1664 if argv:
1689 if argv:
1665 msg = _('unrecognized arguments: %s')
1690 msg = _('unrecognized arguments: %s')
1666 self.error(msg % ' '.join(argv))
1691 self.error(msg % ' '.join(argv))
1667 return args
1692 return args
1668
1693
1669 def parse_known_args(self, args=None, namespace=None):
1694 def parse_known_args(self, args=None, namespace=None):
1670 # args default to the system args
1695 # args default to the system args
1671 if args is None:
1696 if args is None:
1672 args = _sys.argv[1:]
1697 args = _sys.argv[1:]
1673
1698
1674 # default Namespace built from parser defaults
1699 # default Namespace built from parser defaults
1675 if namespace is None:
1700 if namespace is None:
1676 namespace = Namespace()
1701 namespace = Namespace()
1677
1702
1678 # add any action defaults that aren't present
1703 # add any action defaults that aren't present
1679 for action in self._actions:
1704 for action in self._actions:
1680 if action.dest is not SUPPRESS:
1705 if action.dest is not SUPPRESS:
1681 if not hasattr(namespace, action.dest):
1706 if not hasattr(namespace, action.dest):
1682 if action.default is not SUPPRESS:
1707 if action.default is not SUPPRESS:
1683 default = action.default
1708 default = action.default
1684 if isinstance(action.default, _basestring):
1709 if isinstance(action.default, _basestring):
1685 default = self._get_value(action, default)
1710 default = self._get_value(action, default)
1686 setattr(namespace, action.dest, default)
1711 setattr(namespace, action.dest, default)
1687
1712
1688 # add any parser defaults that aren't present
1713 # add any parser defaults that aren't present
1689 for dest in self._defaults:
1714 for dest in self._defaults:
1690 if not hasattr(namespace, dest):
1715 if not hasattr(namespace, dest):
1691 setattr(namespace, dest, self._defaults[dest])
1716 setattr(namespace, dest, self._defaults[dest])
1692
1717
1693 # parse the arguments and exit if there are any errors
1718 # parse the arguments and exit if there are any errors
1694 try:
1719 try:
1695 return self._parse_known_args(args, namespace)
1720 return self._parse_known_args(args, namespace)
1696 except ArgumentError:
1721 except ArgumentError:
1697 err = _sys.exc_info()[1]
1722 err = _sys.exc_info()[1]
1698 self.error(str(err))
1723 self.error(str(err))
1699
1724
1700 def _parse_known_args(self, arg_strings, namespace):
1725 def _parse_known_args(self, arg_strings, namespace):
1701 # replace arg strings that are file references
1726 # replace arg strings that are file references
1702 if self.fromfile_prefix_chars is not None:
1727 if self.fromfile_prefix_chars is not None:
1703 arg_strings = self._read_args_from_files(arg_strings)
1728 arg_strings = self._read_args_from_files(arg_strings)
1704
1729
1705 # map all mutually exclusive arguments to the other arguments
1730 # map all mutually exclusive arguments to the other arguments
1706 # they can't occur with
1731 # they can't occur with
1707 action_conflicts = {}
1732 action_conflicts = {}
1708 for mutex_group in self._mutually_exclusive_groups:
1733 for mutex_group in self._mutually_exclusive_groups:
1709 group_actions = mutex_group._group_actions
1734 group_actions = mutex_group._group_actions
1710 for i, mutex_action in enumerate(mutex_group._group_actions):
1735 for i, mutex_action in enumerate(mutex_group._group_actions):
1711 conflicts = action_conflicts.setdefault(mutex_action, [])
1736 conflicts = action_conflicts.setdefault(mutex_action, [])
1712 conflicts.extend(group_actions[:i])
1737 conflicts.extend(group_actions[:i])
1713 conflicts.extend(group_actions[i + 1:])
1738 conflicts.extend(group_actions[i + 1:])
1714
1739
1715 # find all option indices, and determine the arg_string_pattern
1740 # find all option indices, and determine the arg_string_pattern
1716 # which has an 'O' if there is an option at an index,
1741 # which has an 'O' if there is an option at an index,
1717 # an 'A' if there is an argument, or a '-' if there is a '--'
1742 # an 'A' if there is an argument, or a '-' if there is a '--'
1718 option_string_indices = {}
1743 option_string_indices = {}
1719 arg_string_pattern_parts = []
1744 arg_string_pattern_parts = []
1720 arg_strings_iter = iter(arg_strings)
1745 arg_strings_iter = iter(arg_strings)
1721 for i, arg_string in enumerate(arg_strings_iter):
1746 for i, arg_string in enumerate(arg_strings_iter):
1722
1747
1723 # all args after -- are non-options
1748 # all args after -- are non-options
1724 if arg_string == '--':
1749 if arg_string == '--':
1725 arg_string_pattern_parts.append('-')
1750 arg_string_pattern_parts.append('-')
1726 for arg_string in arg_strings_iter:
1751 for arg_string in arg_strings_iter:
1727 arg_string_pattern_parts.append('A')
1752 arg_string_pattern_parts.append('A')
1728
1753
1729 # otherwise, add the arg to the arg strings
1754 # otherwise, add the arg to the arg strings
1730 # and note the index if it was an option
1755 # and note the index if it was an option
1731 else:
1756 else:
1732 option_tuple = self._parse_optional(arg_string)
1757 option_tuple = self._parse_optional(arg_string)
1733 if option_tuple is None:
1758 if option_tuple is None:
1734 pattern = 'A'
1759 pattern = 'A'
1735 else:
1760 else:
1736 option_string_indices[i] = option_tuple
1761 option_string_indices[i] = option_tuple
1737 pattern = 'O'
1762 pattern = 'O'
1738 arg_string_pattern_parts.append(pattern)
1763 arg_string_pattern_parts.append(pattern)
1739
1764
1740 # join the pieces together to form the pattern
1765 # join the pieces together to form the pattern
1741 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1766 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1742
1767
1743 # converts arg strings to the appropriate and then takes the action
1768 # converts arg strings to the appropriate and then takes the action
1744 seen_actions = _set()
1769 seen_actions = _set()
1745 seen_non_default_actions = _set()
1770 seen_non_default_actions = _set()
1746
1771
1747 def take_action(action, argument_strings, option_string=None):
1772 def take_action(action, argument_strings, option_string=None):
1748 seen_actions.add(action)
1773 seen_actions.add(action)
1749 argument_values = self._get_values(action, argument_strings)
1774 argument_values = self._get_values(action, argument_strings)
1750
1775
1751 # error if this argument is not allowed with other previously
1776 # error if this argument is not allowed with other previously
1752 # seen arguments, assuming that actions that use the default
1777 # seen arguments, assuming that actions that use the default
1753 # value don't really count as "present"
1778 # value don't really count as "present"
1754 if argument_values is not action.default:
1779 if argument_values is not action.default:
1755 seen_non_default_actions.add(action)
1780 seen_non_default_actions.add(action)
1756 for conflict_action in action_conflicts.get(action, []):
1781 for conflict_action in action_conflicts.get(action, []):
1757 if conflict_action in seen_non_default_actions:
1782 if conflict_action in seen_non_default_actions:
1758 msg = _('not allowed with argument %s')
1783 msg = _('not allowed with argument %s')
1759 action_name = _get_action_name(conflict_action)
1784 action_name = _get_action_name(conflict_action)
1760 raise ArgumentError(action, msg % action_name)
1785 raise ArgumentError(action, msg % action_name)
1761
1786
1762 # take the action if we didn't receive a SUPPRESS value
1787 # take the action if we didn't receive a SUPPRESS value
1763 # (e.g. from a default)
1788 # (e.g. from a default)
1764 if argument_values is not SUPPRESS:
1789 if argument_values is not SUPPRESS:
1765 action(self, namespace, argument_values, option_string)
1790 action(self, namespace, argument_values, option_string)
1766
1791
1767 # function to convert arg_strings into an optional action
1792 # function to convert arg_strings into an optional action
1768 def consume_optional(start_index):
1793 def consume_optional(start_index):
1769
1794
1770 # get the optional identified at this index
1795 # get the optional identified at this index
1771 option_tuple = option_string_indices[start_index]
1796 option_tuple = option_string_indices[start_index]
1772 action, option_string, explicit_arg = option_tuple
1797 action, option_string, explicit_arg = option_tuple
1773
1798
1774 # identify additional optionals in the same arg string
1799 # identify additional optionals in the same arg string
1775 # (e.g. -xyz is the same as -x -y -z if no args are required)
1800 # (e.g. -xyz is the same as -x -y -z if no args are required)
1776 match_argument = self._match_argument
1801 match_argument = self._match_argument
1777 action_tuples = []
1802 action_tuples = []
1778 while True:
1803 while True:
1779
1804
1780 # if we found no optional action, skip it
1805 # if we found no optional action, skip it
1781 if action is None:
1806 if action is None:
1782 extras.append(arg_strings[start_index])
1807 extras.append(arg_strings[start_index])
1783 return start_index + 1
1808 return start_index + 1
1784
1809
1785 # if there is an explicit argument, try to match the
1810 # if there is an explicit argument, try to match the
1786 # optional's string arguments to only this
1811 # optional's string arguments to only this
1787 if explicit_arg is not None:
1812 if explicit_arg is not None:
1788 arg_count = match_argument(action, 'A')
1813 arg_count = match_argument(action, 'A')
1789
1814
1790 # if the action is a single-dash option and takes no
1815 # if the action is a single-dash option and takes no
1791 # arguments, try to parse more single-dash options out
1816 # arguments, try to parse more single-dash options out
1792 # of the tail of the option string
1817 # of the tail of the option string
1793 chars = self.prefix_chars
1818 chars = self.prefix_chars
1794 if arg_count == 0 and option_string[1] not in chars:
1819 if arg_count == 0 and option_string[1] not in chars:
1795 action_tuples.append((action, [], option_string))
1820 action_tuples.append((action, [], option_string))
1796 for char in self.prefix_chars:
1821 for char in self.prefix_chars:
1797 option_string = char + explicit_arg[0]
1822 option_string = char + explicit_arg[0]
1798 explicit_arg = explicit_arg[1:] or None
1823 explicit_arg = explicit_arg[1:] or None
1799 optionals_map = self._option_string_actions
1824 optionals_map = self._option_string_actions
1800 if option_string in optionals_map:
1825 if option_string in optionals_map:
1801 action = optionals_map[option_string]
1826 action = optionals_map[option_string]
1802 break
1827 break
1803 else:
1828 else:
1804 msg = _('ignored explicit argument %r')
1829 msg = _('ignored explicit argument %r')
1805 raise ArgumentError(action, msg % explicit_arg)
1830 raise ArgumentError(action, msg % explicit_arg)
1806
1831
1807 # if the action expect exactly one argument, we've
1832 # if the action expect exactly one argument, we've
1808 # successfully matched the option; exit the loop
1833 # successfully matched the option; exit the loop
1809 elif arg_count == 1:
1834 elif arg_count == 1:
1810 stop = start_index + 1
1835 stop = start_index + 1
1811 args = [explicit_arg]
1836 args = [explicit_arg]
1812 action_tuples.append((action, args, option_string))
1837 action_tuples.append((action, args, option_string))
1813 break
1838 break
1814
1839
1815 # error if a double-dash option did not use the
1840 # error if a double-dash option did not use the
1816 # explicit argument
1841 # explicit argument
1817 else:
1842 else:
1818 msg = _('ignored explicit argument %r')
1843 msg = _('ignored explicit argument %r')
1819 raise ArgumentError(action, msg % explicit_arg)
1844 raise ArgumentError(action, msg % explicit_arg)
1820
1845
1821 # if there is no explicit argument, try to match the
1846 # if there is no explicit argument, try to match the
1822 # optional's string arguments with the following strings
1847 # optional's string arguments with the following strings
1823 # if successful, exit the loop
1848 # if successful, exit the loop
1824 else:
1849 else:
1825 start = start_index + 1
1850 start = start_index + 1
1826 selected_patterns = arg_strings_pattern[start:]
1851 selected_patterns = arg_strings_pattern[start:]
1827 arg_count = match_argument(action, selected_patterns)
1852 arg_count = match_argument(action, selected_patterns)
1828 stop = start + arg_count
1853 stop = start + arg_count
1829 args = arg_strings[start:stop]
1854 args = arg_strings[start:stop]
1830 action_tuples.append((action, args, option_string))
1855 action_tuples.append((action, args, option_string))
1831 break
1856 break
1832
1857
1833 # add the Optional to the list and return the index at which
1858 # add the Optional to the list and return the index at which
1834 # the Optional's string args stopped
1859 # the Optional's string args stopped
1835 assert action_tuples
1860 assert action_tuples
1836 for action, args, option_string in action_tuples:
1861 for action, args, option_string in action_tuples:
1837 take_action(action, args, option_string)
1862 take_action(action, args, option_string)
1838 return stop
1863 return stop
1839
1864
1840 # the list of Positionals left to be parsed; this is modified
1865 # the list of Positionals left to be parsed; this is modified
1841 # by consume_positionals()
1866 # by consume_positionals()
1842 positionals = self._get_positional_actions()
1867 positionals = self._get_positional_actions()
1843
1868
1844 # function to convert arg_strings into positional actions
1869 # function to convert arg_strings into positional actions
1845 def consume_positionals(start_index):
1870 def consume_positionals(start_index):
1846 # match as many Positionals as possible
1871 # match as many Positionals as possible
1847 match_partial = self._match_arguments_partial
1872 match_partial = self._match_arguments_partial
1848 selected_pattern = arg_strings_pattern[start_index:]
1873 selected_pattern = arg_strings_pattern[start_index:]
1849 arg_counts = match_partial(positionals, selected_pattern)
1874 arg_counts = match_partial(positionals, selected_pattern)
1850
1875
1851 # slice off the appropriate arg strings for each Positional
1876 # slice off the appropriate arg strings for each Positional
1852 # and add the Positional and its args to the list
1877 # and add the Positional and its args to the list
1853 for action, arg_count in zip(positionals, arg_counts):
1878 for action, arg_count in zip(positionals, arg_counts):
1854 args = arg_strings[start_index: start_index + arg_count]
1879 args = arg_strings[start_index: start_index + arg_count]
1855 start_index += arg_count
1880 start_index += arg_count
1856 take_action(action, args)
1881 take_action(action, args)
1857
1882
1858 # slice off the Positionals that we just parsed and return the
1883 # slice off the Positionals that we just parsed and return the
1859 # index at which the Positionals' string args stopped
1884 # index at which the Positionals' string args stopped
1860 positionals[:] = positionals[len(arg_counts):]
1885 positionals[:] = positionals[len(arg_counts):]
1861 return start_index
1886 return start_index
1862
1887
1863 # consume Positionals and Optionals alternately, until we have
1888 # consume Positionals and Optionals alternately, until we have
1864 # passed the last option string
1889 # passed the last option string
1865 extras = []
1890 extras = []
1866 start_index = 0
1891 start_index = 0
1867 if option_string_indices:
1892 if option_string_indices:
1868 max_option_string_index = max(option_string_indices)
1893 max_option_string_index = max(option_string_indices)
1869 else:
1894 else:
1870 max_option_string_index = -1
1895 max_option_string_index = -1
1871 while start_index <= max_option_string_index:
1896 while start_index <= max_option_string_index:
1872
1897
1873 # consume any Positionals preceding the next option
1898 # consume any Positionals preceding the next option
1874 next_option_string_index = min([
1899 next_option_string_index = min([
1875 index
1900 index
1876 for index in option_string_indices
1901 for index in option_string_indices
1877 if index >= start_index])
1902 if index >= start_index])
1878 if start_index != next_option_string_index:
1903 if start_index != next_option_string_index:
1879 positionals_end_index = consume_positionals(start_index)
1904 positionals_end_index = consume_positionals(start_index)
1880
1905
1881 # only try to parse the next optional if we didn't consume
1906 # only try to parse the next optional if we didn't consume
1882 # the option string during the positionals parsing
1907 # the option string during the positionals parsing
1883 if positionals_end_index > start_index:
1908 if positionals_end_index > start_index:
1884 start_index = positionals_end_index
1909 start_index = positionals_end_index
1885 continue
1910 continue
1886 else:
1911 else:
1887 start_index = positionals_end_index
1912 start_index = positionals_end_index
1888
1913
1889 # if we consumed all the positionals we could and we're not
1914 # if we consumed all the positionals we could and we're not
1890 # at the index of an option string, there were extra arguments
1915 # at the index of an option string, there were extra arguments
1891 if start_index not in option_string_indices:
1916 if start_index not in option_string_indices:
1892 strings = arg_strings[start_index:next_option_string_index]
1917 strings = arg_strings[start_index:next_option_string_index]
1893 extras.extend(strings)
1918 extras.extend(strings)
1894 start_index = next_option_string_index
1919 start_index = next_option_string_index
1895
1920
1896 # consume the next optional and any arguments for it
1921 # consume the next optional and any arguments for it
1897 start_index = consume_optional(start_index)
1922 start_index = consume_optional(start_index)
1898
1923
1899 # consume any positionals following the last Optional
1924 # consume any positionals following the last Optional
1900 stop_index = consume_positionals(start_index)
1925 stop_index = consume_positionals(start_index)
1901
1926
1902 # if we didn't consume all the argument strings, there were extras
1927 # if we didn't consume all the argument strings, there were extras
1903 extras.extend(arg_strings[stop_index:])
1928 extras.extend(arg_strings[stop_index:])
1904
1929
1905 # if we didn't use all the Positional objects, there were too few
1930 # if we didn't use all the Positional objects, there were too few
1906 # arg strings supplied.
1931 # arg strings supplied.
1907 if positionals:
1932 if positionals:
1908 self.error(_('too few arguments'))
1933 self.error(_('too few arguments'))
1909
1934
1910 # make sure all required actions were present
1935 # make sure all required actions were present
1911 for action in self._actions:
1936 for action in self._actions:
1912 if action.required:
1937 if action.required:
1913 if action not in seen_actions:
1938 if action not in seen_actions:
1914 name = _get_action_name(action)
1939 name = _get_action_name(action)
1915 self.error(_('argument %s is required') % name)
1940 self.error(_('argument %s is required') % name)
1916
1941
1917 # make sure all required groups had one option present
1942 # make sure all required groups had one option present
1918 for group in self._mutually_exclusive_groups:
1943 for group in self._mutually_exclusive_groups:
1919 if group.required:
1944 if group.required:
1920 for action in group._group_actions:
1945 for action in group._group_actions:
1921 if action in seen_non_default_actions:
1946 if action in seen_non_default_actions:
1922 break
1947 break
1923
1948
1924 # if no actions were used, report the error
1949 # if no actions were used, report the error
1925 else:
1950 else:
1926 names = [_get_action_name(action)
1951 names = [_get_action_name(action)
1927 for action in group._group_actions
1952 for action in group._group_actions
1928 if action.help is not SUPPRESS]
1953 if action.help is not SUPPRESS]
1929 msg = _('one of the arguments %s is required')
1954 msg = _('one of the arguments %s is required')
1930 self.error(msg % ' '.join(names))
1955 self.error(msg % ' '.join(names))
1931
1956
1932 # return the updated namespace and the extra arguments
1957 # return the updated namespace and the extra arguments
1933 return namespace, extras
1958 return namespace, extras
1934
1959
1935 def _read_args_from_files(self, arg_strings):
1960 def _read_args_from_files(self, arg_strings):
1936 # expand arguments referencing files
1961 # expand arguments referencing files
1937 new_arg_strings = []
1962 new_arg_strings = []
1938 for arg_string in arg_strings:
1963 for arg_string in arg_strings:
1939
1964
1940 # for regular arguments, just add them back into the list
1965 # for regular arguments, just add them back into the list
1941 if arg_string[0] not in self.fromfile_prefix_chars:
1966 if arg_string[0] not in self.fromfile_prefix_chars:
1942 new_arg_strings.append(arg_string)
1967 new_arg_strings.append(arg_string)
1943
1968
1944 # replace arguments referencing files with the file content
1969 # replace arguments referencing files with the file content
1945 else:
1970 else:
1946 try:
1971 try:
1947 args_file = open(arg_string[1:])
1972 args_file = open(arg_string[1:])
1948 try:
1973 try:
1949 arg_strings = args_file.read().splitlines()
1974 arg_strings = args_file.read().splitlines()
1950 arg_strings = self._read_args_from_files(arg_strings)
1975 arg_strings = self._read_args_from_files(arg_strings)
1951 new_arg_strings.extend(arg_strings)
1976 new_arg_strings.extend(arg_strings)
1952 finally:
1977 finally:
1953 args_file.close()
1978 args_file.close()
1954 except IOError:
1979 except IOError:
1955 err = _sys.exc_info()[1]
1980 err = _sys.exc_info()[1]
1956 self.error(str(err))
1981 self.error(str(err))
1957
1982
1958 # return the modified argument list
1983 # return the modified argument list
1959 return new_arg_strings
1984 return new_arg_strings
1960
1985
1961 def _match_argument(self, action, arg_strings_pattern):
1986 def _match_argument(self, action, arg_strings_pattern):
1962 # match the pattern for this action to the arg strings
1987 # match the pattern for this action to the arg strings
1963 nargs_pattern = self._get_nargs_pattern(action)
1988 nargs_pattern = self._get_nargs_pattern(action)
1964 match = _re.match(nargs_pattern, arg_strings_pattern)
1989 match = _re.match(nargs_pattern, arg_strings_pattern)
1965
1990
1966 # raise an exception if we weren't able to find a match
1991 # raise an exception if we weren't able to find a match
1967 if match is None:
1992 if match is None:
1968 nargs_errors = {
1993 nargs_errors = {
1969 None: _('expected one argument'),
1994 None: _('expected one argument'),
1970 OPTIONAL: _('expected at most one argument'),
1995 OPTIONAL: _('expected at most one argument'),
1971 ONE_OR_MORE: _('expected at least one argument'),
1996 ONE_OR_MORE: _('expected at least one argument'),
1972 }
1997 }
1973 default = _('expected %s argument(s)') % action.nargs
1998 default = _('expected %s argument(s)') % action.nargs
1974 msg = nargs_errors.get(action.nargs, default)
1999 msg = nargs_errors.get(action.nargs, default)
1975 raise ArgumentError(action, msg)
2000 raise ArgumentError(action, msg)
1976
2001
1977 # return the number of arguments matched
2002 # return the number of arguments matched
1978 return len(match.group(1))
2003 return len(match.group(1))
1979
2004
1980 def _match_arguments_partial(self, actions, arg_strings_pattern):
2005 def _match_arguments_partial(self, actions, arg_strings_pattern):
1981 # progressively shorten the actions list by slicing off the
2006 # progressively shorten the actions list by slicing off the
1982 # final actions until we find a match
2007 # final actions until we find a match
1983 result = []
2008 result = []
1984 for i in range(len(actions), 0, -1):
2009 for i in range(len(actions), 0, -1):
1985 actions_slice = actions[:i]
2010 actions_slice = actions[:i]
1986 pattern = ''.join([self._get_nargs_pattern(action)
2011 pattern = ''.join([self._get_nargs_pattern(action)
1987 for action in actions_slice])
2012 for action in actions_slice])
1988 match = _re.match(pattern, arg_strings_pattern)
2013 match = _re.match(pattern, arg_strings_pattern)
1989 if match is not None:
2014 if match is not None:
1990 result.extend([len(string) for string in match.groups()])
2015 result.extend([len(string) for string in match.groups()])
1991 break
2016 break
1992
2017
1993 # return the list of arg string counts
2018 # return the list of arg string counts
1994 return result
2019 return result
1995
2020
1996 def _parse_optional(self, arg_string):
2021 def _parse_optional(self, arg_string):
1997 # if it's an empty string, it was meant to be a positional
2022 # if it's an empty string, it was meant to be a positional
1998 if not arg_string:
2023 if not arg_string:
1999 return None
2024 return None
2000
2025
2001 # if it doesn't start with a prefix, it was meant to be positional
2026 # if it doesn't start with a prefix, it was meant to be positional
2002 if not arg_string[0] in self.prefix_chars:
2027 if not arg_string[0] in self.prefix_chars:
2003 return None
2028 return None
2004
2029
2005 # if it's just dashes, it was meant to be positional
2030 # if it's just dashes, it was meant to be positional
2006 if not arg_string.strip('-'):
2031 if not arg_string.strip('-'):
2007 return None
2032 return None
2008
2033
2009 # if the option string is present in the parser, return the action
2034 # if the option string is present in the parser, return the action
2010 if arg_string in self._option_string_actions:
2035 if arg_string in self._option_string_actions:
2011 action = self._option_string_actions[arg_string]
2036 action = self._option_string_actions[arg_string]
2012 return action, arg_string, None
2037 return action, arg_string, None
2013
2038
2039 # if the option string before the "=" is present, return the action
2040 if '=' in arg_string:
2041 option_string, explicit_arg = arg_string.split('=', 1)
2042 if option_string in self._option_string_actions:
2043 action = self._option_string_actions[option_string]
2044 return action, option_string, explicit_arg
2045
2014 # search through all possible prefixes of the option string
2046 # search through all possible prefixes of the option string
2015 # and all actions in the parser for possible interpretations
2047 # and all actions in the parser for possible interpretations
2016 option_tuples = self._get_option_tuples(arg_string)
2048 option_tuples = self._get_option_tuples(arg_string)
2017
2049
2018 # if multiple actions match, the option string was ambiguous
2050 # if multiple actions match, the option string was ambiguous
2019 if len(option_tuples) > 1:
2051 if len(option_tuples) > 1:
2020 options = ', '.join([option_string
2052 options = ', '.join([option_string
2021 for action, option_string, explicit_arg in option_tuples])
2053 for action, option_string, explicit_arg in option_tuples])
2022 tup = arg_string, options
2054 tup = arg_string, options
2023 self.error(_('ambiguous option: %s could match %s') % tup)
2055 self.error(_('ambiguous option: %s could match %s') % tup)
2024
2056
2025 # if exactly one action matched, this segmentation is good,
2057 # if exactly one action matched, this segmentation is good,
2026 # so return the parsed action
2058 # so return the parsed action
2027 elif len(option_tuples) == 1:
2059 elif len(option_tuples) == 1:
2028 option_tuple, = option_tuples
2060 option_tuple, = option_tuples
2029 return option_tuple
2061 return option_tuple
2030
2062
2031 # if it was not found as an option, but it looks like a negative
2063 # if it was not found as an option, but it looks like a negative
2032 # number, it was meant to be positional
2064 # number, it was meant to be positional
2033 # unless there are negative-number-like options
2065 # unless there are negative-number-like options
2034 if self._negative_number_matcher.match(arg_string):
2066 if self._negative_number_matcher.match(arg_string):
2035 if not self._has_negative_number_optionals:
2067 if not self._has_negative_number_optionals:
2036 return None
2068 return None
2037
2069
2038 # if it contains a space, it was meant to be a positional
2070 # if it contains a space, it was meant to be a positional
2039 if ' ' in arg_string:
2071 if ' ' in arg_string:
2040 return None
2072 return None
2041
2073
2042 # it was meant to be an optional but there is no such option
2074 # it was meant to be an optional but there is no such option
2043 # in this parser (though it might be a valid option in a subparser)
2075 # in this parser (though it might be a valid option in a subparser)
2044 return None, arg_string, None
2076 return None, arg_string, None
2045
2077
2046 def _get_option_tuples(self, option_string):
2078 def _get_option_tuples(self, option_string):
2047 result = []
2079 result = []
2048
2080
2049 # option strings starting with two prefix characters are only
2081 # option strings starting with two prefix characters are only
2050 # split at the '='
2082 # split at the '='
2051 chars = self.prefix_chars
2083 chars = self.prefix_chars
2052 if option_string[0] in chars and option_string[1] in chars:
2084 if option_string[0] in chars and option_string[1] in chars:
2053 if '=' in option_string:
2085 if '=' in option_string:
2054 option_prefix, explicit_arg = option_string.split('=', 1)
2086 option_prefix, explicit_arg = option_string.split('=', 1)
2055 else:
2087 else:
2056 option_prefix = option_string
2088 option_prefix = option_string
2057 explicit_arg = None
2089 explicit_arg = None
2058 for option_string in self._option_string_actions:
2090 for option_string in self._option_string_actions:
2059 if option_string.startswith(option_prefix):
2091 if option_string.startswith(option_prefix):
2060 action = self._option_string_actions[option_string]
2092 action = self._option_string_actions[option_string]
2061 tup = action, option_string, explicit_arg
2093 tup = action, option_string, explicit_arg
2062 result.append(tup)
2094 result.append(tup)
2063
2095
2064 # single character options can be concatenated with their arguments
2096 # single character options can be concatenated with their arguments
2065 # but multiple character options always have to have their argument
2097 # but multiple character options always have to have their argument
2066 # separate
2098 # separate
2067 elif option_string[0] in chars and option_string[1] not in chars:
2099 elif option_string[0] in chars and option_string[1] not in chars:
2068 option_prefix = option_string
2100 option_prefix = option_string
2069 explicit_arg = None
2101 explicit_arg = None
2070 short_option_prefix = option_string[:2]
2102 short_option_prefix = option_string[:2]
2071 short_explicit_arg = option_string[2:]
2103 short_explicit_arg = option_string[2:]
2072
2104
2073 for option_string in self._option_string_actions:
2105 for option_string in self._option_string_actions:
2074 if option_string == short_option_prefix:
2106 if option_string == short_option_prefix:
2075 action = self._option_string_actions[option_string]
2107 action = self._option_string_actions[option_string]
2076 tup = action, option_string, short_explicit_arg
2108 tup = action, option_string, short_explicit_arg
2077 result.append(tup)
2109 result.append(tup)
2078 elif option_string.startswith(option_prefix):
2110 elif option_string.startswith(option_prefix):
2079 action = self._option_string_actions[option_string]
2111 action = self._option_string_actions[option_string]
2080 tup = action, option_string, explicit_arg
2112 tup = action, option_string, explicit_arg
2081 result.append(tup)
2113 result.append(tup)
2082
2114
2083 # shouldn't ever get here
2115 # shouldn't ever get here
2084 else:
2116 else:
2085 self.error(_('unexpected option string: %s') % option_string)
2117 self.error(_('unexpected option string: %s') % option_string)
2086
2118
2087 # return the collected option tuples
2119 # return the collected option tuples
2088 return result
2120 return result
2089
2121
2090 def _get_nargs_pattern(self, action):
2122 def _get_nargs_pattern(self, action):
2091 # in all examples below, we have to allow for '--' args
2123 # in all examples below, we have to allow for '--' args
2092 # which are represented as '-' in the pattern
2124 # which are represented as '-' in the pattern
2093 nargs = action.nargs
2125 nargs = action.nargs
2094
2126
2095 # the default (None) is assumed to be a single argument
2127 # the default (None) is assumed to be a single argument
2096 if nargs is None:
2128 if nargs is None:
2097 nargs_pattern = '(-*A-*)'
2129 nargs_pattern = '(-*A-*)'
2098
2130
2099 # allow zero or one arguments
2131 # allow zero or one arguments
2100 elif nargs == OPTIONAL:
2132 elif nargs == OPTIONAL:
2101 nargs_pattern = '(-*A?-*)'
2133 nargs_pattern = '(-*A?-*)'
2102
2134
2103 # allow zero or more arguments
2135 # allow zero or more arguments
2104 elif nargs == ZERO_OR_MORE:
2136 elif nargs == ZERO_OR_MORE:
2105 nargs_pattern = '(-*[A-]*)'
2137 nargs_pattern = '(-*[A-]*)'
2106
2138
2107 # allow one or more arguments
2139 # allow one or more arguments
2108 elif nargs == ONE_OR_MORE:
2140 elif nargs == ONE_OR_MORE:
2109 nargs_pattern = '(-*A[A-]*)'
2141 nargs_pattern = '(-*A[A-]*)'
2110
2142
2143 # allow any number of options or arguments
2144 elif nargs == REMAINDER:
2145 nargs_pattern = '([-AO]*)'
2146
2111 # allow one argument followed by any number of options or arguments
2147 # allow one argument followed by any number of options or arguments
2112 elif nargs is PARSER:
2148 elif nargs == PARSER:
2113 nargs_pattern = '(-*A[-AO]*)'
2149 nargs_pattern = '(-*A[-AO]*)'
2114
2150
2115 # all others should be integers
2151 # all others should be integers
2116 else:
2152 else:
2117 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2153 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2118
2154
2119 # if this is an optional action, -- is not allowed
2155 # if this is an optional action, -- is not allowed
2120 if action.option_strings:
2156 if action.option_strings:
2121 nargs_pattern = nargs_pattern.replace('-*', '')
2157 nargs_pattern = nargs_pattern.replace('-*', '')
2122 nargs_pattern = nargs_pattern.replace('-', '')
2158 nargs_pattern = nargs_pattern.replace('-', '')
2123
2159
2124 # return the pattern
2160 # return the pattern
2125 return nargs_pattern
2161 return nargs_pattern
2126
2162
2127 # ========================
2163 # ========================
2128 # Value conversion methods
2164 # Value conversion methods
2129 # ========================
2165 # ========================
2130 def _get_values(self, action, arg_strings):
2166 def _get_values(self, action, arg_strings):
2131 # for everything but PARSER args, strip out '--'
2167 # for everything but PARSER args, strip out '--'
2132 if action.nargs is not PARSER:
2168 if action.nargs not in [PARSER, REMAINDER]:
2133 arg_strings = [s for s in arg_strings if s != '--']
2169 arg_strings = [s for s in arg_strings if s != '--']
2134
2170
2135 # optional argument produces a default when not present
2171 # optional argument produces a default when not present
2136 if not arg_strings and action.nargs == OPTIONAL:
2172 if not arg_strings and action.nargs == OPTIONAL:
2137 if action.option_strings:
2173 if action.option_strings:
2138 value = action.const
2174 value = action.const
2139 else:
2175 else:
2140 value = action.default
2176 value = action.default
2141 if isinstance(value, _basestring):
2177 if isinstance(value, _basestring):
2142 value = self._get_value(action, value)
2178 value = self._get_value(action, value)
2143 self._check_value(action, value)
2179 self._check_value(action, value)
2144
2180
2145 # when nargs='*' on a positional, if there were no command-line
2181 # when nargs='*' on a positional, if there were no command-line
2146 # args, use the default if it is anything other than None
2182 # args, use the default if it is anything other than None
2147 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2183 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2148 not action.option_strings):
2184 not action.option_strings):
2149 if action.default is not None:
2185 if action.default is not None:
2150 value = action.default
2186 value = action.default
2151 else:
2187 else:
2152 value = arg_strings
2188 value = arg_strings
2153 self._check_value(action, value)
2189 self._check_value(action, value)
2154
2190
2155 # single argument or optional argument produces a single value
2191 # single argument or optional argument produces a single value
2156 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2192 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2157 arg_string, = arg_strings
2193 arg_string, = arg_strings
2158 value = self._get_value(action, arg_string)
2194 value = self._get_value(action, arg_string)
2159 self._check_value(action, value)
2195 self._check_value(action, value)
2160
2196
2197 # REMAINDER arguments convert all values, checking none
2198 elif action.nargs == REMAINDER:
2199 value = [self._get_value(action, v) for v in arg_strings]
2200
2161 # PARSER arguments convert all values, but check only the first
2201 # PARSER arguments convert all values, but check only the first
2162 elif action.nargs is PARSER:
2202 elif action.nargs == PARSER:
2163 value = [self._get_value(action, v) for v in arg_strings]
2203 value = [self._get_value(action, v) for v in arg_strings]
2164 self._check_value(action, value[0])
2204 self._check_value(action, value[0])
2165
2205
2166 # all other types of nargs produce a list
2206 # all other types of nargs produce a list
2167 else:
2207 else:
2168 value = [self._get_value(action, v) for v in arg_strings]
2208 value = [self._get_value(action, v) for v in arg_strings]
2169 for v in value:
2209 for v in value:
2170 self._check_value(action, v)
2210 self._check_value(action, v)
2171
2211
2172 # return the converted value
2212 # return the converted value
2173 return value
2213 return value
2174
2214
2175 def _get_value(self, action, arg_string):
2215 def _get_value(self, action, arg_string):
2176 type_func = self._registry_get('type', action.type, action.type)
2216 type_func = self._registry_get('type', action.type, action.type)
2177 if not hasattr(type_func, '__call__'):
2217 if not _callable(type_func):
2178 if not hasattr(type_func, '__bases__'): # classic classes
2218 msg = _('%r is not callable')
2179 msg = _('%r is not callable')
2219 raise ArgumentError(action, msg % type_func)
2180 raise ArgumentError(action, msg % type_func)
2181
2220
2182 # convert the value to the appropriate type
2221 # convert the value to the appropriate type
2183 try:
2222 try:
2184 result = type_func(arg_string)
2223 result = type_func(arg_string)
2185
2224
2186 # TypeErrors or ValueErrors indicate errors
2225 # ArgumentTypeErrors indicate errors
2226 except ArgumentTypeError:
2227 name = getattr(action.type, '__name__', repr(action.type))
2228 msg = str(_sys.exc_info()[1])
2229 raise ArgumentError(action, msg)
2230
2231 # TypeErrors or ValueErrors also indicate errors
2187 except (TypeError, ValueError):
2232 except (TypeError, ValueError):
2188 name = getattr(action.type, '__name__', repr(action.type))
2233 name = getattr(action.type, '__name__', repr(action.type))
2189 msg = _('invalid %s value: %r')
2234 msg = _('invalid %s value: %r')
2190 raise ArgumentError(action, msg % (name, arg_string))
2235 raise ArgumentError(action, msg % (name, arg_string))
2191
2236
2192 # return the converted value
2237 # return the converted value
2193 return result
2238 return result
2194
2239
2195 def _check_value(self, action, value):
2240 def _check_value(self, action, value):
2196 # converted value must be one of the choices (if specified)
2241 # converted value must be one of the choices (if specified)
2197 if action.choices is not None and value not in action.choices:
2242 if action.choices is not None and value not in action.choices:
2198 tup = value, ', '.join(map(repr, action.choices))
2243 tup = value, ', '.join(map(repr, action.choices))
2199 msg = _('invalid choice: %r (choose from %s)') % tup
2244 msg = _('invalid choice: %r (choose from %s)') % tup
2200 raise ArgumentError(action, msg)
2245 raise ArgumentError(action, msg)
2201
2246
2202 # =======================
2247 # =======================
2203 # Help-formatting methods
2248 # Help-formatting methods
2204 # =======================
2249 # =======================
2205 def format_usage(self):
2250 def format_usage(self):
2206 formatter = self._get_formatter()
2251 formatter = self._get_formatter()
2207 formatter.add_usage(self.usage, self._actions,
2252 formatter.add_usage(self.usage, self._actions,
2208 self._mutually_exclusive_groups)
2253 self._mutually_exclusive_groups)
2209 return formatter.format_help()
2254 return formatter.format_help()
2210
2255
2211 def format_help(self):
2256 def format_help(self):
2212 formatter = self._get_formatter()
2257 formatter = self._get_formatter()
2213
2258
2214 # usage
2259 # usage
2215 formatter.add_usage(self.usage, self._actions,
2260 formatter.add_usage(self.usage, self._actions,
2216 self._mutually_exclusive_groups)
2261 self._mutually_exclusive_groups)
2217
2262
2218 # description
2263 # description
2219 formatter.add_text(self.description)
2264 formatter.add_text(self.description)
2220
2265
2221 # positionals, optionals and user-defined groups
2266 # positionals, optionals and user-defined groups
2222 for action_group in self._action_groups:
2267 for action_group in self._action_groups:
2223 formatter.start_section(action_group.title)
2268 formatter.start_section(action_group.title)
2224 formatter.add_text(action_group.description)
2269 formatter.add_text(action_group.description)
2225 formatter.add_arguments(action_group._group_actions)
2270 formatter.add_arguments(action_group._group_actions)
2226 formatter.end_section()
2271 formatter.end_section()
2227
2272
2228 # epilog
2273 # epilog
2229 formatter.add_text(self.epilog)
2274 formatter.add_text(self.epilog)
2230
2275
2231 # determine help from format above
2276 # determine help from format above
2232 return formatter.format_help()
2277 return formatter.format_help()
2233
2278
2234 def format_version(self):
2279 def format_version(self):
2235 formatter = self._get_formatter()
2280 formatter = self._get_formatter()
2236 formatter.add_text(self.version)
2281 formatter.add_text(self.version)
2237 return formatter.format_help()
2282 return formatter.format_help()
2238
2283
2239 def _get_formatter(self):
2284 def _get_formatter(self):
2240 return self.formatter_class(prog=self.prog)
2285 return self.formatter_class(prog=self.prog)
2241
2286
2242 # =====================
2287 # =====================
2243 # Help-printing methods
2288 # Help-printing methods
2244 # =====================
2289 # =====================
2245 def print_usage(self, file=None):
2290 def print_usage(self, file=None):
2246 self._print_message(self.format_usage(), file)
2291 self._print_message(self.format_usage(), file)
2247
2292
2248 def print_help(self, file=None):
2293 def print_help(self, file=None):
2249 self._print_message(self.format_help(), file)
2294 self._print_message(self.format_help(), file)
2250
2295
2251 def print_version(self, file=None):
2296 def print_version(self, file=None):
2252 self._print_message(self.format_version(), file)
2297 self._print_message(self.format_version(), file)
2253
2298
2254 def _print_message(self, message, file=None):
2299 def _print_message(self, message, file=None):
2255 if message:
2300 if message:
2256 if file is None:
2301 if file is None:
2257 file = _sys.stderr
2302 file = _sys.stderr
2258 file.write(message)
2303 file.write(message)
2259
2304
2260 # ===============
2305 # ===============
2261 # Exiting methods
2306 # Exiting methods
2262 # ===============
2307 # ===============
2263 def exit(self, status=0, message=None):
2308 def exit(self, status=0, message=None):
2264 if message:
2309 if message:
2265 _sys.stderr.write(message)
2310 self._print_message(message, _sys.stderr)
2266 _sys.exit(status)
2311 _sys.exit(status)
2267
2312
2268 def error(self, message):
2313 def error(self, message):
2269 """error(message: string)
2314 """error(message: string)
2270
2315
2271 Prints a usage message incorporating the message to stderr and
2316 Prints a usage message incorporating the message to stderr and
2272 exits.
2317 exits.
2273
2318
2274 If you override this in a subclass, it should not return -- it
2319 If you override this in a subclass, it should not return -- it
2275 should either exit or raise an exception.
2320 should either exit or raise an exception.
2276 """
2321 """
2277 self.print_usage(_sys.stderr)
2322 self.print_usage(_sys.stderr)
2278 self.exit(2, _('%s: error: %s\n') % (self.prog, message))
2323 self.exit(2, _('%s: error: %s\n') % (self.prog, message))
General Comments 0
You need to be logged in to leave comments. Login now