argparse.py 87 KB

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