argparse.py 87 KB

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