argparse.py 95 KB

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