argparse.py 99 KB

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