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