configargparse.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. # -*- coding: utf-8 -*-
  2. import argparse
  3. import os
  4. import re
  5. import sys
  6. import types
  7. import warnings
  8. import functools
  9. if sys.version_info >= (3, 0):
  10. from io import StringIO
  11. else:
  12. from StringIO import StringIO
  13. if sys.version_info < (2, 7):
  14. from ordereddict import OrderedDict
  15. else:
  16. from collections import OrderedDict
  17. ACTION_TYPES_THAT_DONT_NEED_A_VALUE = set([argparse._StoreTrueAction,
  18. argparse._StoreFalseAction, argparse._CountAction,
  19. argparse._StoreConstAction, argparse._AppendConstAction])
  20. # global ArgumentParser instances
  21. _parsers = {}
  22. def init_argument_parser(name=None, **kwargs):
  23. """ Initialise the global argument parser for `name`.
  24. Create a global ArgumentParser instance with the specified `name`,
  25. passing any args other than `name` to the ArgumentParser
  26. constructor. This instance can then be retrieved using
  27. `get_argument_parser(...)`.
  28. """
  29. if name is None:
  30. name = "default"
  31. if name in _parsers:
  32. raise ValueError(("kwargs besides 'name' can only be passed in the"
  33. " first time. '%s' ArgumentParser already exists: %s") % (
  34. name, _parsers[name]))
  35. kwargs.setdefault('formatter_class', argparse.ArgumentDefaultsHelpFormatter)
  36. kwargs.setdefault('conflict_handler', 'resolve')
  37. _parsers[name] = ArgumentParser(**kwargs)
  38. def get_argument_parser(name=None, **kwargs):
  39. """ Get the global argument parser for `name`.
  40. Returns the global ArgumentParser instance with the specified
  41. `name`. The first time this function is called, a new
  42. ArgumentParser instance will be created for the given name, and
  43. any args other than `name` will be passed on to the ArgumentParser
  44. constructor.
  45. """
  46. if name is None:
  47. name = "default"
  48. if len(kwargs) > 0 or name not in _parsers:
  49. init_argument_parser(name, **kwargs)
  50. return _parsers[name]
  51. class ArgumentDefaultsRawHelpFormatter(
  52. argparse.ArgumentDefaultsHelpFormatter,
  53. argparse.RawTextHelpFormatter,
  54. argparse.RawDescriptionHelpFormatter):
  55. """HelpFormatter that adds default values AND doesn't do line-wrapping"""
  56. pass
  57. class ConfigFileParser(object):
  58. """This abstract class can be extended to add support for new config file
  59. formats"""
  60. def get_syntax_description(self):
  61. """Returns a string describing the config file syntax."""
  62. raise NotImplementedError("get_syntax_description(..) not implemented")
  63. def parse(self, stream):
  64. """Parses the keys and values from a config file.
  65. NOTE: For keys that were specified to configargparse as
  66. action="store_true" or "store_false", the config file value must be
  67. one of: "yes", "no", "true", "false". Otherwise an error will be raised.
  68. Args:
  69. stream: A config file input stream (such as an open file object).
  70. Returns:
  71. OrderedDict of items where the keys have type string and the
  72. values have type either string or list (eg. to support config file
  73. formats like YAML which allow lists).
  74. """
  75. raise NotImplementedError("parse(..) not implemented")
  76. def serialize(self, items):
  77. """Does the inverse of config parsing by taking parsed values and
  78. converting them back to a string representing config file contents.
  79. Args:
  80. items: an OrderedDict of items to be converted to the config file
  81. format. Keys should be strings, and values should be either strings
  82. or lists.
  83. Returns:
  84. Contents of config file as a string
  85. """
  86. raise NotImplementedError("serialize(..) not implemented")
  87. class ConfigFileParserException(Exception):
  88. """Raised when config file parsing failed."""
  89. class DefaultConfigFileParser(ConfigFileParser):
  90. """Based on a simplified subset of INI and YAML formats. Here is the
  91. supported syntax:
  92. # this is a comment
  93. ; this is also a comment (.ini style)
  94. --- # lines that start with --- are ignored (yaml style)
  95. -------------------
  96. [section] # .ini-style section names are treated as comments
  97. # how to specify a key-value pair (all of these are equivalent):
  98. name value # key is case sensitive: "Name" isn't "name"
  99. name = value # (.ini style) (white space is ignored, so name = value same as name=value)
  100. name: value # (yaml style)
  101. --name value # (argparse style)
  102. # how to set a flag arg (eg. arg which has action="store_true")
  103. --name
  104. name
  105. name = True # "True" and "true" are the same
  106. # how to specify a list arg (eg. arg which has action="append")
  107. fruit = [apple, orange, lemon]
  108. indexes = [1, 12, 35 , 40]
  109. """
  110. def get_syntax_description(self):
  111. msg = ("Config file syntax allows: key=value, flag=true, stuff=[a,b,c] "
  112. "(for details, see syntax at https://goo.gl/R74nmi).")
  113. return msg
  114. def parse(self, stream):
  115. """Parses the keys + values from a config file."""
  116. items = OrderedDict()
  117. for i, line in enumerate(stream):
  118. line = line.strip()
  119. if not line or line[0] in ["#", ";", "["] or line.startswith("---"):
  120. continue
  121. white_space = "\\s*"
  122. key = "(?P<key>[^:=;#\s]+?)"
  123. value1 = white_space+"[:=]"+white_space+"(?P<value>[^;#]+?)"
  124. value2 = white_space+"[\s]"+white_space+"(?P<value>[^;#\s]+?)"
  125. comment = white_space+"(?P<comment>\\s[;#].*)?"
  126. key_only_match = re.match("^" + key + comment + "$", line)
  127. if key_only_match:
  128. key = key_only_match.group("key")
  129. items[key] = "true"
  130. continue
  131. key_value_match = re.match("^"+key+value1+comment+"$", line) or \
  132. re.match("^"+key+value2+comment+"$", line)
  133. if key_value_match:
  134. key = key_value_match.group("key")
  135. value = key_value_match.group("value")
  136. if value.startswith("[") and value.endswith("]"):
  137. # handle special case of lists
  138. value = [elem.strip() for elem in value[1:-1].split(",")]
  139. items[key] = value
  140. continue
  141. raise ConfigFileParserException("Unexpected line %s in %s: %s" % (i,
  142. getattr(stream, 'name', 'stream'), line))
  143. return items
  144. def serialize(self, items):
  145. """Does the inverse of config parsing by taking parsed values and
  146. converting them back to a string representing config file contents.
  147. """
  148. r = StringIO()
  149. for key, value in items.items():
  150. if type(value) == list:
  151. # handle special case of lists
  152. value = "["+", ".join(value)+"]"
  153. r.write("%s = %s\n" % (key, value))
  154. return r.getvalue()
  155. class YAMLConfigFileParser(ConfigFileParser):
  156. """Parses YAML config files. Depends on the PyYAML module.
  157. https://pypi.python.org/pypi/PyYAML
  158. """
  159. def get_syntax_description(self):
  160. msg = ("The config file uses YAML syntax and must represent a YAML "
  161. "'mapping' (for details, see http://learn.getgrav.org/advanced/yaml).")
  162. return msg
  163. def _load_yaml(self):
  164. """lazy-import PyYAML so that configargparse doesn't have to dependend
  165. on it unless this parser is used."""
  166. try:
  167. import yaml
  168. except ImportError:
  169. raise ConfigFileParserException("Could not import yaml. "
  170. "It can be installed by running 'pip install PyYAML'")
  171. return yaml
  172. def parse(self, stream):
  173. """Parses the keys and values from a config file."""
  174. yaml = self._load_yaml()
  175. try:
  176. parsed_obj = yaml.safe_load(stream)
  177. except Exception as e:
  178. raise ConfigFileParserException("Couldn't parse config file: %s" % e)
  179. if type(parsed_obj) != dict:
  180. raise ConfigFileParserException("The config file doesn't appear to "
  181. "contain 'key: value' pairs (aka. a YAML mapping). "
  182. "yaml.load('%s') returned type '%s' instead of 'dict'." % (
  183. getattr(stream, 'name', 'stream'), type(parsed_obj).__name__))
  184. result = OrderedDict()
  185. for key, value in parsed_obj.items():
  186. if type(value) == list:
  187. result[key] = value
  188. else:
  189. result[key] = str(value)
  190. return result
  191. def serialize(self, items, default_flow_style=False):
  192. """Does the inverse of config parsing by taking parsed values and
  193. converting them back to a string representing config file contents.
  194. Args:
  195. default_flow_style: defines serialization format (see PyYAML docs)
  196. """
  197. # lazy-import so there's no dependency on yaml unless this class is used
  198. yaml = self._load_yaml()
  199. # it looks like ordering can't be preserved: http://pyyaml.org/ticket/29
  200. items = dict(items)
  201. return yaml.dump(items, default_flow_style=default_flow_style)
  202. # used while parsing args to keep track of where they came from
  203. _COMMAND_LINE_SOURCE_KEY = "command_line"
  204. _ENV_VAR_SOURCE_KEY = "environment_variables"
  205. _CONFIG_FILE_SOURCE_KEY = "config_file"
  206. _DEFAULTS_SOURCE_KEY = "defaults"
  207. class ArgumentParser(argparse.ArgumentParser):
  208. """Drop-in replacement for argparse.ArgumentParser that adds support for
  209. environment variables and .ini or .yaml-style config files.
  210. """
  211. def __init__(self,
  212. prog=None,
  213. usage=None,
  214. description=None,
  215. epilog=None,
  216. version=None,
  217. parents=[],
  218. formatter_class=argparse.HelpFormatter,
  219. prefix_chars='-',
  220. fromfile_prefix_chars=None,
  221. argument_default=None,
  222. conflict_handler='error',
  223. add_help=True,
  224. add_config_file_help=True,
  225. add_env_var_help=True,
  226. auto_env_var_prefix=None,
  227. default_config_files=[],
  228. ignore_unknown_config_file_keys=False,
  229. config_file_parser_class=DefaultConfigFileParser,
  230. args_for_setting_config_path=[],
  231. config_arg_is_required=False,
  232. config_arg_help_message="config file path",
  233. args_for_writing_out_config_file=[],
  234. write_out_config_file_arg_help_message="takes the current command line "
  235. "args and writes them out to a config file at the given path, then "
  236. "exits",
  237. allow_abbrev=True, # new in python 3.5
  238. ):
  239. """Supports all the same args as the argparse.ArgumentParser
  240. constructor, as well as the following additional args.
  241. Additional Args:
  242. add_config_file_help: Whether to add a description of config file
  243. syntax to the help message.
  244. add_env_var_help: Whether to add something to the help message for
  245. args that can be set through environment variables.
  246. auto_env_var_prefix: If set to a string instead of None, all config-
  247. file-settable options will become also settable via environment
  248. variables whose names are this prefix followed by the config
  249. file key, all in upper case. (eg. setting this to "foo_" will
  250. allow an arg like "--my-arg" to also be set via the FOO_MY_ARG
  251. environment variable)
  252. default_config_files: When specified, this list of config files will
  253. be parsed in order, with the values from each config file
  254. taking precedence over pervious ones. This allows an application
  255. to look for config files in multiple standard locations such as
  256. the install directory, home directory, and current directory:
  257. ["<install dir>/app_config.ini",
  258. "~/.my_app_config.ini",
  259. "./app_config.txt"]
  260. ignore_unknown_config_file_keys: If true, settings that are found
  261. in a config file but don't correspond to any defined
  262. configargparse args will be ignored. If false, they will be
  263. processed and appended to the commandline like other args, and
  264. can be retrieved using parse_known_args() instead of parse_args()
  265. config_file_parser_class: configargparse.ConfigFileParser subclass
  266. which determines the config file format. configargparse comes
  267. with DefaultConfigFileParser and YAMLConfigFileParser.
  268. args_for_setting_config_path: A list of one or more command line
  269. args to be used for specifying the config file path
  270. (eg. ["-c", "--config-file"]). Default: []
  271. config_arg_is_required: When args_for_setting_config_path is set,
  272. set this to True to always require users to provide a config path.
  273. config_arg_help_message: the help message to use for the
  274. args listed in args_for_setting_config_path.
  275. args_for_writing_out_config_file: A list of one or more command line
  276. args to use for specifying a config file output path. If
  277. provided, these args cause configargparse to write out a config
  278. file with settings based on the other provided commandline args,
  279. environment variants and defaults, and then to exit.
  280. (eg. ["-w", "--write-out-config-file"]). Default: []
  281. write_out_config_file_arg_help_message: The help message to use for
  282. the args in args_for_writing_out_config_file.
  283. allow_abbrev: Allows long options to be abbreviated if the
  284. abbreviation is unambiguous. Default: True
  285. """
  286. self._add_config_file_help = add_config_file_help
  287. self._add_env_var_help = add_env_var_help
  288. self._auto_env_var_prefix = auto_env_var_prefix
  289. # extract kwargs that can be passed to the super constructor
  290. kwargs_for_super = dict((k, v) for k, v in locals().items() if k in [
  291. "prog", "usage", "description", "epilog", "version", "parents",
  292. "formatter_class", "prefix_chars", "fromfile_prefix_chars",
  293. "argument_default", "conflict_handler", "add_help"])
  294. if sys.version_info >= (3, 3) and "version" in kwargs_for_super:
  295. del kwargs_for_super["version"] # version arg deprecated in v3.3
  296. if sys.version_info >= (3, 5):
  297. kwargs_for_super["allow_abbrev"] = allow_abbrev # new option in v3.5
  298. argparse.ArgumentParser.__init__(self, **kwargs_for_super)
  299. # parse the additionial args
  300. if config_file_parser_class is None:
  301. self._config_file_parser = DefaultConfigFileParser()
  302. else:
  303. self._config_file_parser = config_file_parser_class()
  304. self._default_config_files = default_config_files
  305. self._ignore_unknown_config_file_keys = ignore_unknown_config_file_keys
  306. if args_for_setting_config_path:
  307. self.add_argument(*args_for_setting_config_path, dest="config_file",
  308. required=config_arg_is_required, help=config_arg_help_message,
  309. is_config_file_arg=True)
  310. if args_for_writing_out_config_file:
  311. self.add_argument(*args_for_writing_out_config_file,
  312. dest="write_out_config_file_to_this_path",
  313. metavar="CONFIG_OUTPUT_PATH",
  314. help=write_out_config_file_arg_help_message,
  315. is_write_out_config_file_arg=True)
  316. def parse_args(self, args = None, namespace = None,
  317. config_file_contents = None, env_vars = os.environ):
  318. """Supports all the same args as the ArgumentParser.parse_args(..),
  319. as well as the following additional args.
  320. Additional Args:
  321. args: a list of args as in argparse, or a string (eg. "-x -y bla")
  322. config_file_contents: String. Used for testing.
  323. env_vars: Dictionary. Used for testing.
  324. """
  325. args, argv = self.parse_known_args(args = args,
  326. namespace = namespace,
  327. config_file_contents = config_file_contents,
  328. env_vars = env_vars)
  329. if argv:
  330. self.error('unrecognized arguments: %s' % ' '.join(argv))
  331. return args
  332. def parse_known_args(self, args = None, namespace = None,
  333. config_file_contents = None, env_vars = os.environ):
  334. """Supports all the same args as the ArgumentParser.parse_args(..),
  335. as well as the following additional args.
  336. Additional Args:
  337. args: a list of args as in argparse, or a string (eg. "-x -y bla")
  338. config_file_contents: String. Used for testing.
  339. env_vars: Dictionary. Used for testing.
  340. """
  341. if args is None:
  342. args = sys.argv[1:]
  343. elif type(args) == str:
  344. args = args.split()
  345. else:
  346. args = list(args)
  347. # normalize args by converting args like --key=value to --key value
  348. normalized_args = list()
  349. for arg in args:
  350. if arg and arg[0] in self.prefix_chars and '=' in arg:
  351. key, value = arg.split('=', 1)
  352. normalized_args.append(key)
  353. normalized_args.append(value)
  354. else:
  355. normalized_args.append(arg)
  356. args = normalized_args
  357. for a in self._actions:
  358. a.is_positional_arg = not a.option_strings
  359. # maps a string describing the source (eg. env var) to a settings dict
  360. # to keep track of where values came from (used by print_values()).
  361. # The settings dicts for env vars and config files will then map
  362. # the config key to an (argparse Action obj, string value) 2-tuple.
  363. self._source_to_settings = OrderedDict()
  364. if args:
  365. a_v_pair = (None, list(args)) # copy args list to isolate changes
  366. self._source_to_settings[_COMMAND_LINE_SOURCE_KEY] = {'': a_v_pair}
  367. # handle auto_env_var_prefix __init__ arg by setting a.env_var as needed
  368. if self._auto_env_var_prefix is not None:
  369. for a in self._actions:
  370. config_file_keys = self.get_possible_config_keys(a)
  371. if config_file_keys and not (a.env_var or a.is_positional_arg
  372. or a.is_config_file_arg or a.is_write_out_config_file_arg or
  373. type(a) == argparse._HelpAction):
  374. stripped_config_file_key = config_file_keys[0].strip(
  375. self.prefix_chars)
  376. a.env_var = (self._auto_env_var_prefix +
  377. stripped_config_file_key).replace('-', '_').upper()
  378. # add env var settings to the commandline that aren't there already
  379. env_var_args = []
  380. actions_with_env_var_values = [a for a in self._actions
  381. if not a.is_positional_arg and a.env_var and a.env_var in env_vars
  382. and not already_on_command_line(args, a.option_strings)]
  383. for action in actions_with_env_var_values:
  384. key = action.env_var
  385. value = env_vars[key] # TODO parse env var values here to allow lists?
  386. env_var_args += self.convert_item_to_command_line_arg(
  387. action, key, value)
  388. args = env_var_args + args
  389. if env_var_args:
  390. self._source_to_settings[_ENV_VAR_SOURCE_KEY] = OrderedDict(
  391. [(a.env_var, (a, env_vars[a.env_var]))
  392. for a in actions_with_env_var_values])
  393. # before parsing any config files, check if -h was specified.
  394. supports_help_arg = any(
  395. a for a in self._actions if type(a) == argparse._HelpAction)
  396. skip_config_file_parsing = supports_help_arg and (
  397. "-h" in args or "--help" in args)
  398. # prepare for reading config file(s)
  399. known_config_keys = dict((config_key, action) for action in self._actions
  400. for config_key in self.get_possible_config_keys(action))
  401. # open the config file(s)
  402. config_streams = []
  403. if config_file_contents:
  404. stream = StringIO(config_file_contents)
  405. stream.name = "method arg"
  406. config_streams = [stream]
  407. elif not skip_config_file_parsing:
  408. config_streams = self._open_config_files(args)
  409. # parse each config file
  410. for stream in reversed(config_streams):
  411. try:
  412. config_items = self._config_file_parser.parse(stream)
  413. except ConfigFileParserException as e:
  414. self.error(e)
  415. finally:
  416. if hasattr(stream, "close"):
  417. stream.close()
  418. # add each config item to the commandline unless it's there already
  419. config_args = []
  420. for key, value in config_items.items():
  421. if key in known_config_keys:
  422. action = known_config_keys[key]
  423. discard_this_key = already_on_command_line(
  424. args, action.option_strings)
  425. else:
  426. action = None
  427. discard_this_key = self._ignore_unknown_config_file_keys or \
  428. already_on_command_line(
  429. args,
  430. self.get_command_line_key_for_unknown_config_file_setting(key))
  431. if not discard_this_key:
  432. config_args += self.convert_item_to_command_line_arg(
  433. action, key, value)
  434. source_key = "%s|%s" %(_CONFIG_FILE_SOURCE_KEY, stream.name)
  435. if source_key not in self._source_to_settings:
  436. self._source_to_settings[source_key] = OrderedDict()
  437. self._source_to_settings[source_key][key] = (action, value)
  438. args = config_args + args
  439. # save default settings for use by print_values()
  440. default_settings = OrderedDict()
  441. for action in self._actions:
  442. cares_about_default_value = (not action.is_positional_arg or
  443. action.nargs in [OPTIONAL, ZERO_OR_MORE])
  444. if (already_on_command_line(args, action.option_strings) or
  445. not cares_about_default_value or
  446. action.default is None or
  447. action.default == SUPPRESS or
  448. type(action) in ACTION_TYPES_THAT_DONT_NEED_A_VALUE):
  449. continue
  450. else:
  451. if action.option_strings:
  452. key = action.option_strings[-1]
  453. else:
  454. key = action.dest
  455. default_settings[key] = (action, str(action.default))
  456. if default_settings:
  457. self._source_to_settings[_DEFAULTS_SOURCE_KEY] = default_settings
  458. # parse all args (including commandline, config file, and env var)
  459. namespace, unknown_args = argparse.ArgumentParser.parse_known_args(
  460. self, args=args, namespace=namespace)
  461. # handle any args that have is_write_out_config_file_arg set to true
  462. user_write_out_config_file_arg_actions = [a for a in self._actions
  463. if getattr(a, "is_write_out_config_file_arg", False)]
  464. if user_write_out_config_file_arg_actions:
  465. output_file_paths = []
  466. for action in user_write_out_config_file_arg_actions:
  467. # check if the user specified this arg on the commandline
  468. output_file_path = getattr(namespace, action.dest, None)
  469. if output_file_path:
  470. # validate the output file path
  471. try:
  472. with open(output_file_path, "w") as output_file:
  473. output_file_paths.append(output_file_path)
  474. except IOError as e:
  475. raise ValueError("Couldn't open %s for writing: %s" % (
  476. output_file_path, e))
  477. if output_file_paths:
  478. # generate the config file contents
  479. config_items = self.get_items_for_config_file_output(
  480. self._source_to_settings, namespace)
  481. file_contents = self._config_file_parser.serialize(config_items)
  482. for output_file_path in output_file_paths:
  483. with open(output_file_path, "w") as output_file:
  484. output_file.write(file_contents)
  485. if len(output_file_paths) == 1:
  486. output_file_paths = output_file_paths[0]
  487. self.exit(0, "Wrote config file to " + str(output_file_paths))
  488. return namespace, unknown_args
  489. def get_command_line_key_for_unknown_config_file_setting(self, key):
  490. """Compute a commandline arg key to be used for a config file setting
  491. that doesn't correspond to any defined configargparse arg (and so
  492. doesn't have a user-specified commandline arg key).
  493. Args:
  494. key: The config file key that was being set.
  495. """
  496. key_without_prefix_chars = key.strip(self.prefix_chars)
  497. command_line_key = self.prefix_chars[0]*2 + key_without_prefix_chars
  498. return command_line_key
  499. def get_items_for_config_file_output(self, source_to_settings,
  500. parsed_namespace):
  501. """Converts the given settings back to a dictionary that can be passed
  502. to ConfigFormatParser.serialize(..).
  503. Args:
  504. source_to_settings: the dictionary described in parse_known_args()
  505. parsed_namespace: namespace object created within parse_known_args()
  506. Returns:
  507. an OrderedDict where keys are strings and values are either strings
  508. or lists
  509. """
  510. config_file_items = OrderedDict()
  511. for source, settings in source_to_settings.items():
  512. if source == _COMMAND_LINE_SOURCE_KEY:
  513. _, existing_command_line_args = settings['']
  514. for action in self._actions:
  515. config_file_keys = self.get_possible_config_keys(action)
  516. if config_file_keys and not action.is_positional_arg and \
  517. already_on_command_line(existing_command_line_args,
  518. action.option_strings):
  519. value = getattr(parsed_namespace, action.dest, None)
  520. if value is not None:
  521. if type(value) is bool:
  522. value = str(value).lower()
  523. config_file_items[config_file_keys[0]] = value
  524. elif source == _ENV_VAR_SOURCE_KEY:
  525. for key, (action, value) in settings.items():
  526. config_file_keys = self.get_possible_config_keys(action)
  527. if config_file_keys:
  528. value = getattr(parsed_namespace, action.dest, None)
  529. if value is not None:
  530. config_file_items[config_file_keys[0]] = value
  531. elif source.startswith(_CONFIG_FILE_SOURCE_KEY):
  532. for key, (action, value) in settings.items():
  533. config_file_items[key] = value
  534. elif source == _DEFAULTS_SOURCE_KEY:
  535. for key, (action, value) in settings.items():
  536. config_file_keys = self.get_possible_config_keys(action)
  537. if config_file_keys:
  538. value = getattr(parsed_namespace, action.dest, None)
  539. if value is not None:
  540. config_file_items[config_file_keys[0]] = value
  541. return config_file_items
  542. def convert_item_to_command_line_arg(self, action, key, value):
  543. """Converts a config file or env var key + value to a list of
  544. commandline args to append to the commandline.
  545. Args:
  546. action: The argparse Action object for this setting, or None if this
  547. config file setting doesn't correspond to any defined
  548. configargparse arg.
  549. key: string (config file key or env var name)
  550. value: parsed value of type string or list
  551. """
  552. args = []
  553. if action is None:
  554. command_line_key = \
  555. self.get_command_line_key_for_unknown_config_file_setting(key)
  556. else:
  557. command_line_key = action.option_strings[-1]
  558. # handle boolean value
  559. if action is not None and type(action) in ACTION_TYPES_THAT_DONT_NEED_A_VALUE:
  560. if value.lower() in ("true", "false", "yes", "no"):
  561. args.append( command_line_key )
  562. else:
  563. self.error("Unexpected value for %s: '%s'. Expecting 'true', "
  564. "'false', 'yes', or 'no'" % (key, value))
  565. elif type(value) == list:
  566. if action is not None and type(action) != argparse._AppendAction:
  567. self.error(("%s can't be set to a list '%s' unless its "
  568. "action type is changed to 'append'") % (key, value))
  569. for list_elem in value:
  570. args.append( command_line_key )
  571. args.append( str(list_elem) )
  572. elif type(value) == str:
  573. args.append( command_line_key )
  574. args.append( value )
  575. else:
  576. raise ValueError("Unexpected value type %s for value: %s" % (
  577. type(value), value))
  578. return args
  579. def get_possible_config_keys(self, action):
  580. """This method decides which actions can be set in a config file and
  581. what their keys will be. It returns a list of 0 or more config keys that
  582. can be used to set the given action's value in a config file.
  583. """
  584. keys = []
  585. for arg in action.option_strings:
  586. if any([arg.startswith(2*c) for c in self.prefix_chars]):
  587. keys += [arg[2:], arg] # eg. for '--bla' return ['bla', '--bla']
  588. return keys
  589. def _open_config_files(self, command_line_args):
  590. """Tries to parse config file path(s) from within command_line_args.
  591. Returns a list of opened config files, including files specified on the
  592. commandline as well as any default_config_files specified in the
  593. constructor that are present on disk.
  594. Args:
  595. command_line_args: List of all args (already split on spaces)
  596. """
  597. # open any default config files
  598. config_files = [open(f) for f in map(
  599. os.path.expanduser, self._default_config_files) if os.path.isfile(f)]
  600. # list actions with is_config_file_arg=True. Its possible there is more
  601. # than one such arg.
  602. user_config_file_arg_actions = [
  603. a for a in self._actions if getattr(a, "is_config_file_arg", False)]
  604. if not user_config_file_arg_actions:
  605. return config_files
  606. for action in user_config_file_arg_actions:
  607. # try to parse out the config file path by using a clean new
  608. # ArgumentParser that only knows this one arg/action.
  609. arg_parser = argparse.ArgumentParser(
  610. prefix_chars=self.prefix_chars,
  611. add_help=False)
  612. arg_parser._add_action(action)
  613. # make parser not exit on error by replacing its error method.
  614. # Otherwise it sys.exits(..) if, for example, config file
  615. # is_required=True and user doesn't provide it.
  616. def error_method(self, message):
  617. pass
  618. arg_parser.error = types.MethodType(error_method, arg_parser)
  619. # check whether the user provided a value
  620. parsed_arg = arg_parser.parse_known_args(args=command_line_args)
  621. if not parsed_arg:
  622. continue
  623. namespace, _ = parsed_arg
  624. user_config_file = getattr(namespace, action.dest, None)
  625. if not user_config_file:
  626. continue
  627. # validate the user-provided config file path
  628. user_config_file = os.path.expanduser(user_config_file)
  629. if not os.path.isfile(user_config_file):
  630. self.error('File not found: %s' % user_config_file)
  631. config_files += [open(user_config_file)]
  632. return config_files
  633. def format_values(self):
  634. """Returns a string with all args and settings and where they came from
  635. (eg. commandline, config file, enviroment variable or default)
  636. """
  637. source_key_to_display_value_map = {
  638. _COMMAND_LINE_SOURCE_KEY: "Command Line Args: ",
  639. _ENV_VAR_SOURCE_KEY: "Environment Variables:\n",
  640. _CONFIG_FILE_SOURCE_KEY: "Config File (%s):\n",
  641. _DEFAULTS_SOURCE_KEY: "Defaults:\n"
  642. }
  643. r = StringIO()
  644. for source, settings in self._source_to_settings.items():
  645. source = source.split("|")
  646. source = source_key_to_display_value_map[source[0]] % tuple(source[1:])
  647. r.write(source)
  648. for key, (action, value) in settings.items():
  649. if key:
  650. r.write(" %-19s%s\n" % (key+":", value))
  651. else:
  652. if type(value) is str:
  653. r.write(" %s\n" % value)
  654. elif type(value) is list:
  655. r.write(" %s\n" % ' '.join(value))
  656. return r.getvalue()
  657. def print_values(self, file = sys.stdout):
  658. """Prints the format_values() string (to sys.stdout or another file)."""
  659. file.write(self.format_values())
  660. def format_help(self):
  661. msg = ""
  662. added_config_file_help = False
  663. added_env_var_help = False
  664. if self._add_config_file_help:
  665. default_config_files = self._default_config_files
  666. cc = 2*self.prefix_chars[0] # eg. --
  667. config_settable_args = [(arg, a) for a in self._actions for arg in
  668. a.option_strings if self.get_possible_config_keys(a) and not
  669. (a.dest == "help" or a.is_config_file_arg or
  670. a.is_write_out_config_file_arg)]
  671. config_path_actions = [a for a in
  672. self._actions if getattr(a, "is_config_file_arg", False)]
  673. if config_settable_args and (default_config_files or
  674. config_path_actions):
  675. self._add_config_file_help = False # prevent duplication
  676. added_config_file_help = True
  677. msg += ("Args that start with '%s' (eg. %s) can also be set in "
  678. "a config file") % (cc, config_settable_args[0][0])
  679. config_arg_string = " or ".join(a.option_strings[0]
  680. for a in config_path_actions if a.option_strings)
  681. if config_arg_string:
  682. config_arg_string = "specified via " + config_arg_string
  683. if default_config_files or config_arg_string:
  684. msg += " (%s)." % " or ".join(default_config_files +
  685. list(filter(None, [config_arg_string])))
  686. msg += " " + self._config_file_parser.get_syntax_description()
  687. if self._add_env_var_help:
  688. env_var_actions = [(a.env_var, a) for a in self._actions
  689. if getattr(a, "env_var", None)]
  690. for env_var, a in env_var_actions:
  691. env_var_help_string = " [env var: %s]" % env_var
  692. if not a.help:
  693. a.help = ""
  694. if env_var_help_string not in a.help:
  695. a.help += env_var_help_string
  696. added_env_var_help = True
  697. self._add_env_var_help = False # prevent duplication
  698. if added_env_var_help or added_config_file_help:
  699. value_sources = ["defaults"]
  700. if added_config_file_help:
  701. value_sources = ["config file values"] + value_sources
  702. if added_env_var_help:
  703. value_sources = ["environment variables"] + value_sources
  704. msg += (" If an arg is specified in more than one place, then "
  705. "commandline values override %s.") % (
  706. " which override ".join(value_sources))
  707. if msg:
  708. self.description = (self.description or "") + " " + msg
  709. return argparse.ArgumentParser.format_help(self)
  710. def add_argument(self, *args, **kwargs):
  711. """
  712. This method supports the same args as ArgumentParser.add_argument(..)
  713. as well as the additional args below.
  714. Additional Args:
  715. env_var: If set, the value of this environment variable will override
  716. any config file or default values for this arg (but can itself
  717. be overriden on the commandline). Also, if auto_env_var_prefix is
  718. set in the constructor, this env var name will be used instead of
  719. the automatic name.
  720. is_config_file_arg: If True, this arg is treated as a config file path
  721. This provides an alternative way to specify config files in place of
  722. the ArgumentParser(fromfile_prefix_chars=..) mechanism.
  723. Default: False
  724. is_write_out_config_file_arg: If True, this arg will be treated as a
  725. config file path, and, when it is specified, will cause
  726. configargparse to write all current commandline args to this file
  727. as config options and then exit.
  728. Default: False
  729. """
  730. env_var = kwargs.pop("env_var", None)
  731. is_config_file_arg = kwargs.pop(
  732. "is_config_file_arg", None) or kwargs.pop(
  733. "is_config_file", None) # for backward compat.
  734. is_write_out_config_file_arg = kwargs.pop(
  735. "is_write_out_config_file_arg", None)
  736. action = self.original_add_argument_method(*args, **kwargs)
  737. action.is_positional_arg = not action.option_strings
  738. action.env_var = env_var
  739. action.is_config_file_arg = is_config_file_arg
  740. action.is_write_out_config_file_arg = is_write_out_config_file_arg
  741. if action.is_positional_arg and env_var:
  742. raise ValueError("env_var can't be set for a positional arg.")
  743. if action.is_config_file_arg and type(action) != argparse._StoreAction:
  744. raise ValueError("arg with is_config_file_arg=True must have "
  745. "action='store'")
  746. if action.is_write_out_config_file_arg:
  747. error_prefix = "arg with is_write_out_config_file_arg=True "
  748. if type(action) != argparse._StoreAction:
  749. raise ValueError(error_prefix + "must have action='store'")
  750. if is_config_file_arg:
  751. raise ValueError(error_prefix + "can't also have "
  752. "is_config_file_arg=True")
  753. return action
  754. def already_on_command_line(existing_args_list, potential_command_line_args):
  755. """Utility method for checking if any of the potential_command_line_args is
  756. already present in existing_args.
  757. """
  758. return any(potential_arg in existing_args_list
  759. for potential_arg in potential_command_line_args)
  760. def deprecate_in_favour_of(correct_func):
  761. """ Raise a DeprecationWarning and recommend the correct API. """
  762. @functools.wraps(correct_func)
  763. def wrapper(*args, **kwargs):
  764. warnings.warn(
  765. "This API will be removed, use ‘{correct}’ instead".format(
  766. correct=correct_func.__name__),
  767. DeprecationWarning)
  768. result = correct_func(*args, **kwargs)
  769. return result
  770. return wrapper
  771. # wrap ArgumentParser's add_argument(..) method with the one above
  772. argparse._ActionsContainer.original_add_argument_method = argparse._ActionsContainer.add_argument
  773. argparse._ActionsContainer.add_argument = add_argument
  774. # add all public classes and constants from argparse module's namespace to this
  775. # module's namespace so that the 2 modules are truly interchangeable
  776. HelpFormatter = argparse.HelpFormatter
  777. RawDescriptionHelpFormatter = argparse.RawDescriptionHelpFormatter
  778. RawTextHelpFormatter = argparse.RawTextHelpFormatter
  779. ArgumentDefaultsHelpFormatter = argparse.ArgumentDefaultsHelpFormatter
  780. ArgumentError = argparse.ArgumentError
  781. ArgumentTypeError = argparse.ArgumentTypeError
  782. Action = argparse.Action
  783. FileType = argparse.FileType
  784. Namespace = argparse.Namespace
  785. ONE_OR_MORE = argparse.ONE_OR_MORE
  786. OPTIONAL = argparse.OPTIONAL
  787. REMAINDER = argparse.REMAINDER
  788. SUPPRESS = argparse.SUPPRESS
  789. ZERO_OR_MORE = argparse.ZERO_OR_MORE
  790. # Deprecated PEP-8 incompatible API names.
  791. initArgumentParser = deprecate_in_favour_of(init_argument_parser)
  792. getArgumentParser = deprecate_in_favour_of(get_argument_parser)
  793. getArgParser = getArgumentParser
  794. getParser = getArgumentParser
  795. # Create shorter aliases for the key methods and class names.
  796. get_arg_parser = get_argument_parser
  797. get_parser = get_argument_parser
  798. ArgParser = ArgumentParser
  799. Parser = ArgumentParser
  800. argparse._ActionsContainer.add_arg = argparse._ActionsContainer.add_argument
  801. argparse._ActionsContainer.add = argparse._ActionsContainer.add_argument
  802. ArgumentParser.parse = ArgumentParser.parse_args
  803. ArgumentParser.parse_known = ArgumentParser.parse_known_args
  804. RawFormatter = RawDescriptionHelpFormatter
  805. DefaultsFormatter = ArgumentDefaultsHelpFormatter
  806. DefaultsRawFormatter = ArgumentDefaultsRawHelpFormatter