A drop-in replacement for argparse that allows options to also be set via config files and/or environment variables.
| See Also | |
configargparse.ArgumentParser, configargparse.add_argument |
| Class | |
HelpFormatter that adds default values AND doesn't do line-wrapping |
| Class | |
Drop-in replacement for argparse.ArgumentParser that adds support for environment variables and .ini or .yaml-style config files. |
| Class | |
Create a config parser composed of other config file parsers, each given as a ConfigFileParser instance or class (a class is instantiated with no args). |
| Class | |
This abstract class can be extended to add support for new config file formats |
| Class | |
parses INI files using pythons configparser. |
| Class | |
Based on a simplified subset of INI and YAML formats. Here is the supported syntax |
| Class | |
Create a INI parser bounded to the list of provided sections. Optionaly convert multiline strings to list. |
| Class | |
Create a TOML parser bounded to the list of provided sections. Useful to read settings from a project file such as pyproject.toml. |
| Class | |
Parses YAML config files. Depends on the PyYAML module. https://pypi.python.org/pypi/PyYAML |
| Exception | |
Raised when config file parsing failed. |
| Exception | |
Raised when an optional dependency is missing. |
| Function | add |
This method supports the same args as ArgumentParser.add_argument(..) as well as the additional args below. |
| Function | already |
Utility method for checking if any of the potential_command_line_args is already present in existing_args. |
| Function | get |
Returns the global ArgumentParser instance with the given name. The 1st time this function is called, a new ArgumentParser instance will be created for the given name, and any args other than "name" will be passed on to the ArgumentParser constructor. |
| Function | get |
Given some TOML data (as loaded with toml.load()), returns the requested section of the data. Returns None if the section is not found. |
| Function | init |
Creates a global ArgumentParser instance with the given name, passing any args other than "name" to the ArgumentParser constructor. This instance can then be retrieved using get_argument_parser(..) |
| Function | is |
Detect whether a string is a quoted representation. |
| Function | parse |
Parse a TOML section name to a sequence of strings. |
| Function | unquote |
Unquote a maybe quoted string representation. If the string is not detected as being a quoted representation, it returns the same string as passed. It supports all kinds of python quotes: """, ''', " and ... |
| Variable | ACTION |
Undocumented |
| Variable | is |
Undocumented |
| Class | _ |
Remembers the path this arg was given, on the parser that parsed it. |
| Function | _action |
Check whether argparse stores a list of values for an action. |
| Function | _add |
Add a config file's values to result the way argparse will read them. |
| Function | _close |
Close each config file stream, ignoring any error closing one raises. |
| Function | _configparser |
Check whether ConfigparserConfigFileParser.parse() reads a value as a list. |
| Function | _convert |
Convert a parsed arg value to the value a config file should hold for it. |
| Function | _convert |
Convert a value to a plain str, int, float, bool or list of those. |
| Function | _default |
Check whether a default can be written to a config file and read back. |
| Function | _dispatches |
Check whether an action hands the rest of the command line to a subparser. |
| Function | _evaluate |
Evaluate a config file value written as a Python list literal. |
| Function | _is |
Check whether a value is a list for an option that takes any number of values. |
| Function | _keep |
Return a list element as it should be written into a list repr. |
| Function | _list |
Write a list as a Python list literal that ast.literal_eval reads back. |
| Function | _parse |
Turns a config file or env var value written as a list into a list. |
| Function | _parse |
Read a config file or env var value for a count option as a number. |
| Function | _quote |
Write a string the way IniConfigParser.parse() reads back unchanged. |
| Function | _read |
Read one section's keys and values from a configparser.ConfigParser. |
| Function | _replace |
Write an Enum member as its name where the action's type= needs that. |
| Function | _subparsers |
Find a parser and every subparser reachable from it. |
| Constant | _COMMAND |
Undocumented |
| Constant | _CONFIG |
Undocumented |
| Constant | _DEFAULTS |
Undocumented |
| Constant | _ENV |
Undocumented |
| Constant | _QUOTED |
Undocumented |
| Constant | _TRIPLE |
Undocumented |
| Variable | _parsers |
Undocumented |
This method supports the same args as ArgumentParser.add_argument(..) as well as the additional args below.
| Parameters | |
| self | Undocumented |
| *args | Undocumented |
| env | If set, the value of this environment variable will override any config file or default values for this arg (but can itself be overridden on the commandline). Also, if auto_env_var_prefix is set in the constructor, this env var name will be used instead of the automatic name. |
| is | If True, this arg is treated as a config file path This provides an alternative way to specify config files in place of the ArgumentParser(fromfile_prefix_chars=..) mechanism. Default: False |
| is | If True, this arg will be treated as a config file path, and, when it is specified on the command line, will cause configargparse to write all current commandline args to this file as config options and then exit. It can only be set on the command line: a config file key that names it is an error, and it can't be combined with env_var, nor be a positional arg, since a config file value would be indistinguishable from a path the user typed and could overwrite an arbitrary file. Default: False |
| Returns | |
argparse.Action | the new argparse action |
Utility method for checking if any of the potential_command_line_args is already present in existing_args.
| Parameters | |
| existing | the command line args. |
| potential | the option strings to look for. |
| prefix | the chars that start an option. |
| parser | the ArgumentParser the args are for. When given, only the args that parser reads itself are looked at (not those after a subcommand, which argparse hands to the subparser, nor those after '--' or that a REMAINDER positional or option takes), and every form argparse accepts is recognized, such as '-vv' for '-v' or '-Ifoo' for '-I'. Otherwise only an option string on its own or followed by '=value' is, in the args before any '--'. |
| Returns | |
bool | already on command line? |
Returns the global ArgumentParser instance with the given name. The 1st time this function is called, a new ArgumentParser instance will be created for the given name, and any args other than "name" will be passed on to the ArgumentParser constructor.
Given some TOML data (as loaded with toml.load()), returns the requested section of the data. Returns None if the section is not found.
Creates a global ArgumentParser instance with the given name, passing any args other than "name" to the ArgumentParser constructor. This instance can then be retrieved using get_argument_parser(..)
Detect whether a string is a quoted representation.
| Parameters | |
| text | Undocumented |
| triple | Also match tripple quoted strings. |
Parse a TOML section name to a sequence of strings.
The following names are all valid:
"a.b.c" # this is best practice -> returns ("a", "b", "c") " d.e.f " # same as [d.e.f] -> returns ("d", "e", "f") " g . h . i " # same as [g.h.i] -> returns ("g", "h", "i") ' j . "ʞ" . "l" ' # same as [j."ʞ"."l"], double or simple quotes here are supported. -> returns ("j", "ʞ", "l")
Unquote a maybe quoted string representation. If the string is not detected as being a quoted representation, it returns the same string as passed. It supports all kinds of python quotes: """, ''', " and '.
| Parameters | |
| text | Undocumented |
| triple | Also unquote tripple quoted strings. |
| Raises | |
ValueError | If the string is detected as beeing quoted but literal_eval() fails to evaluate it as string. This would be a bug in the regex. |
Check whether argparse stores a list of values for an action.
It does when nargs is '*', '+' or a number, even 1.
| Parameters | |
| action | an argparse action. |
| Returns | |
bool | whether it does |
Add a config file's values to result the way argparse will read them.
Anything that is not a list is converted to a string, since config values are passed to argparse as command line args, and argparse converts them back to a boolean, int or whatever the arg's type is. Keys set to None are left out.
| Parameters | |
| values | the keys and values a YAML or TOML parser read. |
| result | the OrderedDict to add them to. |
Close each config file stream, ignoring any error closing one raises.
| Parameters | |
| streams | (stream, source label) pairs. |
Check whether ConfigparserConfigFileParser.parse() reads a value as a list.
| Parameters | |
| value | the value as written, with newlines replaced by spaces. |
| Returns | |
bool | whether it has square brackets that aren't inside a {...} dict |
Convert a parsed arg value to the value a config file should hold for it.
For a flag (store_true, store_false, store_const or append_const), the config file value says whether to invoke the flag, not what it stores, so it is "true" exactly when the parsed value is (or, for append_const, holds) the one the flag stores. Other booleans are written in lowercase too, so values from the command line and from environment variables are written the same way. A tuple for an option that takes a list of values, such as a default of (640, 480) for nargs=2, is written as a list.
Values of other types, such as a pathlib.Path default, are written as str(), since every config file format can write a string and read it back. (Such a value that argparse made from a string has already been replaced with that string, see ArgumentParser._replace_parsed_values_with_the_strings_they_came_from().)
| Parameters | |
| action | the action the value was parsed for. |
| value | the value the parser stored for the action. |
| Returns | |
object | "true" or "false" for flags and booleans, otherwise the value with anything that isn't a str, int, float, bool or list converted to a str. |
Convert a value to a plain str, int, float, bool or list of those.
An Enum member is written as its value, which is what a type= callable like type=SomeEnum takes back (one that takes its name instead has already been given the name, see _replace_enum_members_its_type_reads_by_name_with_their_names()). Some config file writers only handle the built-in types themselves, so a subclass of one (eg. a str or int Enum's value, or an IntEnum) becomes that built-in type, and anything else becomes a str.
| Parameters | |
| value | a parsed arg value, or an element of a list value. |
| Returns | |
object | the value, with each list element converted the same way |
Check whether a default can be written to a config file and read back.
It can when it is a str, int, float, bool, Enum or path, or a list or tuple of these that isn't empty. Read back, an empty list sets an option to no values, which argparse rejects for nargs='+', and str() of other objects, such as the open file in a default of sys.stdout, isn't anything the option's type= can take.
| Parameters | |
| value | the default, after any string it was converted from has been put back. |
| Returns | |
bool | whether it can |
Check whether an action hands the rest of the command line to a subparser.
Nearly always this is an argparse._SubParsersAction, but a program can register a class of its own for the job, so recognize the shape too: a mapping of subcommand names to parsers, taking the rest of the args.
| Parameters | |
| action | the action to check. |
| Returns | |
bool | whether it dispatches to subparsers |
Evaluate a config file value written as a Python list literal.
| Parameters | |
| text | the value, eg. "['a', 'b']". |
| Returns | |
| the evaluated value |
| Raises | |
ConfigFileParserException | if the text isn't a valid literal. |
Check whether a value is a list for an option that takes any number of values.
| Parameters | |
| action | the action the value is for, or None for an unknown key. |
| value | the value from a config file or env var. |
| Returns | |
bool | whether argparse would read the args after it as more values |
Return a list element as it should be written into a list repr.
| Parameters | |
| value | an element of a list value. |
| Returns | |
object | the value unchanged if ast.literal_eval of its repr gives it back, otherwise str(value) (e.g. for a Path, or inf). |
Write a list as a Python list literal that ast.literal_eval reads back.
| Parameters | |
| value | a list value, whose elements may be lists themselves. |
| Returns | |
str | the literal, with each element (and each element of an inner list) that a literal can't hold, such as a Path or inf, as its str() |
Turns a config file or env var value written as a list into a list.
| Parameters | |
| value | the value as written, eg. '["a", "b"]' or '[a, b]'. |
| Returns | |
| the list, or the value unchanged if it isn't in square brackets |
Read a config file or env var value for a count option as a number.
Accepts anything int() accepts, such as "2", "+2", " 2 ", "2n" (an env var filled from a file often ends in a newline) or "1_000", as long as the number isn't negative: a flag can't be given a negative number of times.
| Parameters | |
| value | the string from the config file or env var. |
| Returns | |
int or None | the number, or None if value isn't a whole number of 0 or more |
Write a string the way IniConfigParser.parse() reads back unchanged.
parse() strips the whitespace around a value, skips an empty one, reads a value in square brackets as a list and one on several lines as a list (if split_ml_text_to_list is set), and unquotes a quoted one. A list element written on a line of its own that starts with '#' or ';' would be read as a comment. A value any of that would change is written as a Python string literal, which parse() unquotes back to the same string.
| Parameters | |
| value | the string to write. |
| Returns | |
str | the value, or its Python string literal |
Read one section's keys and values from a configparser.ConfigParser.
configparser expands %(name)s references while reading values, so a stray % fails here rather than when the file is read.
| Parameters | |
| config | the configparser.ConfigParser the file was read into. |
| section | the name of the section to read. |
| Returns | |
list | the section's (key, value) pairs |
| Raises | |
ConfigFileParserException | if a value's % or %(name)s can't be expanded. |
Write an Enum member as its name where the action's type= needs that.
An Enum member is otherwise written as its value (see _convert_to_types_every_config_file_parser_can_write()), which suits type=SomeEnum, but not a lookup by name such as type=lambda s: SomeEnum[s]. So a member that the type= callable doesn't read back from its value, but does from its name, is replaced with its name.
| Parameters | |
| action | the action the value was parsed for. |
| value | a parsed arg value, or an element of a list value. |
| Returns | |
object | the value, with each such member replaced by its name |
Find a parser and every subparser reachable from it.
| Parameters | |
| parser | the parser to start from. |
| seen | ids of the parsers already visited, so that a subparser leading back to one of its own ancestors doesn't loop forever. |
| Returns | |
list[argparse.ArgumentParser] | the parser and its subparsers |
Undocumented
| Value |
|