configargparse.py 40 KB

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