argparse.py 93 KB

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