argparse.py 96 KB

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