argparse.py 88 KB

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