argparse.py 99 KB

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