argparse.py 85 KB

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