argparse.py 94 KB

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