Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

argparse_compat.py 86KB

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