class ArgumentParser(argparse.ArgumentParser): (source)
Constructor: ArgumentParser(*args, **kwargs)
Drop-in replacement for argparse.ArgumentParser that adds support for
environment variables and .ini or .yaml-style config files.
| Method | __init__ |
Supports args of the argparse.ArgumentParser constructor as **kwargs, as well as the following additional args. |
| Method | convert |
Converts a config file or env var key + value to a list of commandline args to append to the commandline. |
| Method | format |
Undocumented |
| Method | format |
Returns a string with all args and settings and where they came from (eg. commandline, config file, environment variable or default) |
| Method | get |
Compute a commandline arg key to be used for a config file setting that doesn't correspond to any defined configargparse arg (and so doesn't have a user-specified commandline arg key). |
| Method | get |
Converts the given settings back to a dictionary that can be passed to ConfigFileParser.serialize(..). |
| Method | get |
This method decides which actions can be set in a config file and what their keys will be. It returns a list of 0 or more config keys that can be used to set the given action's value in a config file. |
| Method | get |
If called after parse_args() or parse_known_args(), returns a dict whose keys say where values came from, each mapped to a dict of the settings from there: |
| Method | parse |
Supports all the same args as the argparse.ArgumentParser.parse_args(), as well as the following additional args. |
| Method | parse |
Like parse_args(), but lets optional and positional args be intermixed, as argparse.ArgumentParser.parse_intermixed_args() does. |
| Method | parse |
Supports all the same args as the argparse.ArgumentParser.parse_args(), as well as the following additional args. |
| Method | parse |
Like parse_known_args(), but lets optional and positional args be intermixed, as argparse.ArgumentParser.parse_known_intermixed_args() does. |
| Method | print |
Prints the format_values() string (to sys.stdout or another file). |
| Method | write |
Write the given settings to output files. |
| Instance Variable | exit |
Undocumented |
| Method | _add |
Turn the settings from one config file or the env vars into args. |
| Method | _arg |
Check whether an arg names an option with nargs=REMAINDER. |
| Method | _arg |
Check whether argparse reads a command line arg as an option. |
| Method | _could |
Check whether a command line arg could set the given option. |
| Method | _describe |
Says why argparse may not read the given command line arg as a value. |
| Method | _fill |
Give each action the attributes this module's add_argument() sets. |
| Method | _find |
Find where the args this parser parses itself end. |
| Method | _find |
Find the right index to insert config/env var args into the command line. |
| Method | _find |
Find the option an arg names, if its values are the args after it. |
| Method | _find |
Find where the subcommand is on the command line, if there is one. |
| Method | _find |
Find where argparse stops reading this parser's args as options. |
| Method | _get |
Picks the option string that sets a BooleanOptionalAction arg to the value given for it in a config file or env var. |
| Method | _get |
Convert a string to a value for an action, as argparse does, and record the string the value came from. |
| Method | _get |
Convert an action's args to its value, as argparse does, and record whether it was given any. |
| Method | _has |
Check whether this parser has a positional arg with nargs=REMAINDER. |
| Method | _indexes |
Find the args argparse reads as positional args. |
| Method | _insert |
Insert the args that one config file or the env vars set. |
| Method | _names |
Check whether a command line arg would set a write-out-config-file arg. |
| Method | _open |
Tries to parse config file path(s) from within command_line_args. Returns a list of opened config files, including files specified on the commandline as well as any default_config_files specified in the constructor that are present on disk. |
| Method | _option |
Find the option strings that, when already on the command line, mean an env var or config file value for the given action should be dropped. |
| Method | _reject |
Report args that no arg of this parser took, the way argparse does. |
| Method | _replace |
Put back the string a value came from where str() can't stand in for it. |
| Method | _report |
Report an error the way argparse does for its own errors. |
| Method | _synthesized |
Reject synthesized command line args that set a write-out-config-file arg. |
| Method | _write |
Find the write-out-config-file args the given parsers define. |
| Instance Variable | _actions |
Undocumented |
| Instance Variable | _add |
Undocumented |
| Instance Variable | _add |
Undocumented |
| Instance Variable | _argparse |
Undocumented |
| Instance Variable | _auto |
Undocumented |
| Instance Variable | _config |
Undocumented |
| Instance Variable | _config |
Undocumented |
| Instance Variable | _default |
Undocumented |
| Instance Variable | _ignore |
Undocumented |
| Instance Variable | _parsed |
Undocumented |
| Instance Variable | _parsing |
Undocumented |
| Instance Variable | _source |
Undocumented |
| Instance Variable | _write |
Undocumented |
Inherited from ArgumentParser:
| Method | add |
Undocumented |
| Method | convert |
Undocumented |
| Method | error |
error(message: string) |
| Method | exit |
Undocumented |
| Method | format |
Undocumented |
| Method | print |
Undocumented |
| Method | print |
Undocumented |
| Instance Variable | add |
Undocumented |
| Instance Variable | allow |
Undocumented |
| Instance Variable | epilog |
Undocumented |
| Instance Variable | formatter |
Undocumented |
| Instance Variable | fromfile |
Undocumented |
| Instance Variable | prog |
Undocumented |
| Instance Variable | usage |
Undocumented |
| Method | _add |
Undocumented |
| Method | _check |
Undocumented |
| Method | _get |
Undocumented |
| Method | _get |
Undocumented |
| Method | _get |
Undocumented |
| Method | _get |
Undocumented |
| Method | _get |
Undocumented |
| Method | _get |
Undocumented |
| Method | _match |
Undocumented |
| Method | _match |
Undocumented |
| Method | _parse |
Undocumented |
| Method | _parse |
Undocumented |
| Method | _print |
Undocumented |
| Method | _read |
Undocumented |
| Instance Variable | _optionals |
Undocumented |
| Instance Variable | _positionals |
Undocumented |
| Instance Variable | _subparsers |
Undocumented |
Inherited from _AttributeHolder (via ArgumentParser):
| Method | __repr__ |
Undocumented |
| Method | _get |
Undocumented |
Inherited from _ActionsContainer (via ArgumentParser, _AttributeHolder):
| Method | add |
add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...) |
| Method | add |
Undocumented |
| Method | add |
Undocumented |
| Method | get |
Undocumented |
| Method | register |
Undocumented |
| Method | set |
Undocumented |
| Instance Variable | argument |
Undocumented |
| Instance Variable | conflict |
Undocumented |
| Instance Variable | description |
Undocumented |
| Instance Variable | prefix |
Undocumented |
| Method | _add |
Undocumented |
| Method | _check |
Undocumented |
| Method | _get |
Undocumented |
| Method | _get |
Undocumented |
| Method | _get |
Undocumented |
| Method | _handle |
Undocumented |
| Method | _handle |
Undocumented |
| Method | _pop |
Undocumented |
| Method | _registry |
Undocumented |
| Method | _remove |
Undocumented |
| Instance Variable | _action |
Undocumented |
| Instance Variable | _actions |
Undocumented |
| Instance Variable | _defaults |
Undocumented |
| Instance Variable | _has |
Undocumented |
| Instance Variable | _mutually |
Undocumented |
| Instance Variable | _negative |
Undocumented |
| Instance Variable | _option |
Undocumented |
| Instance Variable | _registries |
Undocumented |
argparse.ArgumentParser.__init__Supports args of the argparse.ArgumentParser constructor
as **kwargs, as well as the following additional args.
| Parameters | |
| *args | Undocumented |
| add | Whether to add a description of config file syntax to the help message. |
| add | Whether to add something to the help message for args that can be set through environment variables. |
| auto | If set to a string instead of None, all config- file-settable options will become also settable via environment variables whose names are this prefix followed by the config file key, all in upper case. (eg. setting this to foo_ will allow an arg like --my-arg to also be set via the FOO_MY_ARG environment variable) |
| default | When specified, this list of config files will be parsed in order, with the values from each config file taking precedence over previous ones. This allows an application to look for config files in multiple standard locations such as the install directory, home directory, and/or current directory. Also, shell * syntax can be used to specify all conf files in a directory, which are then parsed in alphabetical order. For example: ["/etc/conf/app_config.ini", "/etc/conf/conf-enabled/*.ini", "~/.my_app_config.ini", "./app_config.txt"] Path entries may be strings, os.PathLike objects (e.g. pathlib.Path), or zero-argument callable functions that return an open file-like object containing config file contents. Any provided callable is invoked each time the parser opens config files, and the returned stream is closed by the parser after parsing. The callable must return a stream. This is useful for sourcing config from non-filesystem locations such as in-memory buffers, secrets managers, or HTTP responses. |
| ignore | If true, settings that are found in a config file but don't correspond to any defined configargparse args will be ignored. If false, they will be processed and appended to the commandline like other args, and can be retrieved using parse_known_args() instead of parse_args() |
| config | function used to open a config file for reading or writing. Needs to return a file-like object. |
| config | a configargparse.ConfigFileParser subclass, or an instance of one, which determines the config file format. configargparse comes with DefaultConfigFileParser, YAMLConfigFileParser, ConfigparserConfigFileParser, IniConfigParser, TomlConfigParser and CompositeConfigParser. The last three take constructor args, so pass them as instances, eg. TomlConfigParser(['tool.my_tool']). |
| args | A list of one or more command line args to be used for specifying the config file path (eg. ["-c", "--config-file"]). Default: [] |
| config | When args_for_setting_config_path is set, set this to True to always require users to provide a config path. |
| config | the help message to use for the args listed in args_for_setting_config_path. |
| args | A list of one or more command line args to use for specifying a config file output path. If provided, these args cause configargparse to write out a config file with settings based on the other provided commandline args, environment variants and defaults, and then to exit. (eg. ["-w", "--write-out-config-file"]). Default: [] These args can only be set on the command line. A config file key that names one is an error, and they can't have an env_var, since either would let whoever controls those overwrite an arbitrary file. |
| write | The help message to use for the args in args_for_writing_out_config_file. |
Converts a config file or env var key + value to a list of commandline args to append to the commandline.
| Parameters | |
| action | The argparse Action object for this setting, or None if this config file setting doesn't correspond to any defined configargparse arg. |
| key | string (config file key or env var name) |
| value | parsed value of type string or list |
| Returns | |
list[str] | args |
Returns a string with all args and settings and where they came from (eg. commandline, config file, environment variable or default)
| Returns | |
str | source to settings string |
Compute a commandline arg key to be used for a config file setting that doesn't correspond to any defined configargparse arg (and so doesn't have a user-specified commandline arg key).
| Parameters | |
| key | The config file key that was being set. |
| Returns | |
str | command line key |
Converts the given settings back to a dictionary that can be passed to ConfigFileParser.serialize(..).
| Parameters | |
| source | the dictionary returned by get_source_to_settings_dict() |
| parsed | namespace object created within parse_known_args() |
| Returns | |
OrderedDict | where keys are strings and values are a str, int, float or bool, or a list whose elements are any of these or lists of them |
If called after parse_args() or parse_known_args(), returns a dict
whose keys say where values came from, each mapped to a dict of the
settings from there:
- "command_line": maps "" to (None, the list of command line args).
- "environment_variables": maps each env var name to
(
argparse.Actionobj, the env var's value). - "config_file|<source>": one key per config file that set anything,
eg. "config_file|/etc/app.conf", or "config_file|method arg" for
config_file_contents passed to parse_args(). Maps each config file
key to (
argparse.Actionobj, or None for a key that no arg has, the value as read, a str or a list). - "defaults": maps each arg's last option string (or dest, for a
positional arg) to (
argparse.Actionobj, str() of its default).
| Returns | |
dict[str, dict[str, tuple]] | source to settings dict |
argparse.ArgumentParser.parse_argsSupports all the same args as the argparse.ArgumentParser.parse_args(),
as well as the following additional args.
| Parameters | |
| args | a list of args as in argparse, or a string (eg. "-x -y bla") |
| namespace | Undocumented |
| config | String. Used for testing. |
| env | Dictionary. Used for testing. |
| Returns | |
argparse.Namespace | namespace |
Like parse_args(), but lets optional and positional args be
intermixed, as argparse.ArgumentParser.parse_intermixed_args() does.
| Parameters | |
| args | a list of args as in argparse, or a string (eg. "-x -y bla") |
| namespace | Undocumented |
| config | String. Used for testing. |
| env | Dictionary. Used for testing. |
| Returns | |
argparse.Namespace | namespace |
argparse.ArgumentParser.parse_known_argsSupports all the same args as the argparse.ArgumentParser.parse_args(),
as well as the following additional args.
| Parameters | |
| args | a list of args as in argparse, or a string (eg. "-x -y bla") |
| namespace | Undocumented |
configstr | |
envdict | |
ignorebool | This flag determines behavior when user specifies --help or -h. If False, it will have the default behavior - printing help and exiting. If True, it won't do either. |
| Returns | |
tuple[argparse.Namespace, list[str]] | tuple namescpace, unknown_args |
Like parse_known_args(), but lets optional and positional args be
intermixed, as argparse.ArgumentParser.parse_known_intermixed_args()
does.
| Parameters | |
| args | a list of args as in argparse, or a string (eg. "-x -y bla") |
| namespace | Undocumented |
configstr | |
envdict | |
ignorebool | see parse_known_args(). |
| Returns | |
tuple[argparse.Namespace, list[str]] | tuple namespace, unknown_args |
Write the given settings to output files.
| Parameters | |
| parsed | namespace object created within parse_known_args() |
| output | any number of file paths to write the config to |
| exit | whether to exit the program after writing the config files |
Turn the settings from one config file or the env vars into args.
| Parameters | |
| args | the command line args so far. |
| actions | (action, key, value) for each setting from the source that isn't set by a higher-priority source. action is None for a config file key that no arg has. |
| source | where the settings came from, for error messages, eg. "in an environment variable". |
| variable | see _insert_args_from_config_file_or_env_vars(), updated in place. |
| flag | the flag actions set by sources that take precedence over the ones still to come, updated in place with this source's flags. |
| Returns | |
tuple | the new command line args, and whether this source's args were added to them (they aren't when one would set a write-out-config-file arg) |
Check whether an arg names an option with nargs=REMAINDER.
Such an option takes every arg after it as its values, options included.
| Parameters | |
| arg | a single command line arg. |
| Returns | |
bool | whether it names one |
Check whether argparse reads a command line arg as an option.
A lone prefix char (eg. '-' for stdin) is a value, and so is a negative number when the parser has no option that looks like one. This uses argparse's own pattern for a negative number, which differs by Python version (from 3.14 it also matches eg. "-1e5").
| Parameters | |
| arg | a single command line arg. |
| Returns | |
bool | whether it is an option (or the '--' separator) rather than a value |
Check whether a command line arg could set the given option.
This covers every form argparse accepts: the option on its own, with its value attached after an = (or, for a short option, straight after it), bundled with other short options, and abbreviated. Where argparse would need to look at the rest of the command line to decide, this says yes, since it is used to reject args that must not reach an option at all, and being wrong in that direction only costs an error message.
| Parameters | |
| arg | a single command line arg. |
| option | an option string of the option to look for. |
| Returns | |
bool | whether the arg could set the option |
Says why argparse may not read the given command line arg as a value.
This is stricter than argparse, which also reads some other args that start with a prefix char as values, such as one that contains a space.
| Parameters | |
arg:str | a command line arg. |
| Returns | |
str | what's wrong with it, worded to follow "<key> can't have", or None if argparse reads it as a value. |
Give each action the attributes this module's add_argument() sets.
An action that didn't go through it, eg. one copied from a plain argparse parser passed as parents=, gets them with their default values, so the code that reads them works the same for every action. With auto_env_var_prefix set, each action that can have an env var and has none gets its automatic one. Both parsing and the help text read these, so this runs before either.
Find the right index to insert config/env var args into the command line.
Inserts at position 0 when a REMAINDER positional exists, otherwise before a subparser command (one before any --) so the parent parser sees injected args first, otherwise before an option with nargs=REMAINDER or the -- separator if present, or before the first optional arg. Falls back to appending.
Find the option an arg names, if its values are the args after it.
| Parameters | |
| arg | a single command line arg that is read as an option. |
| Returns | |
argparse.Action or None | the option named exactly, or by an unambiguous abbreviation of a long option, or None if the arg names none or has its value attached with '=' |
Find where the subcommand is on the command line, if there is one.
An arg that is the value of the option before it, like the first 'build' in '--target build build', isn't the subcommand, so the values of an option named exactly, and taking a set number of them, are skipped the way argparse reads them.
| Parameters | |
| args | the command line args. |
| Returns | |
int or None | the index of the first arg naming a subcommand |
Find where argparse stops reading this parser's args as options.
That is at the '--' separator, with a REMAINDER positional at its first arg, or just after an option with nargs=REMAINDER that comes before any subcommand, since those take every arg from there on, options included.
| Parameters | |
| args | the command line args. |
| Returns | |
int or None | that index, or None if argparse reads them all |
Picks the option string that sets a BooleanOptionalAction arg to the value given for it in a config file or env var.
argparse adds a negative form after some option strings of a BooleanOptionalAction ('--no-foo' after '--foo', and from Python 3.15 also '++no-foo' after '++foo' and '-nofoo' after '-foo'), and sets the arg to False for the negative forms and to True for the rest. A short alias can come first, so the negative forms aren't at a fixed position. A config file key that names a negative form (eg. 'no-feature' for '--no-feature') means the opposite value, so 'no-feature = true' sets the arg to False, just as '--no-feature' would on the command line.
| Parameters | |
| action | The argparse.BooleanOptionalAction to set. |
| key | The config file key or env var name the value came from. |
| value | The boolean value given for that key. |
| Returns | |
list | the option string to add to the command line, or no args if none of the option strings sets that value |
argparse.ArgumentParser._get_valueConvert a string to a value for an action, as argparse does, and record the string the value came from.
argparse converts each command line or env var string this way, and a string default or const too. A type= callable can make a value whose str() it can't read back, such as a dict from json.loads or the open file argparse.FileType makes, so a config file written out for that value holds the recorded string instead (see _replace_parsed_values_with_the_strings_they_came_from()).
| Parameters | |
| action | the action the string is for. |
| arg | the string. |
| Returns | |
object | the value argparse made from it |
argparse.ArgumentParser._get_valuesConvert an action's args to its value, as argparse does, and record whether it was given any.
| Parameters | |
| action | the action the args are for. |
| arg | the args argparse took for it. |
| Returns | |
object | the value argparse made from them |
Find the args argparse reads as positional args.
Options aren't, and neither are an option's values, which are skipped the way argparse reads them: nargs=None or '?' takes the next arg, an int n takes up to n, and '*' or '+' take every arg up to the next option, as long as they aren't options themselves. A value attached with '=' takes nothing more, and an option with nargs=REMAINDER takes everything after it.
| Parameters | |
| args | the command line args. |
| Yields | |
int | the index of each positional arg, in order |
Insert the args that one config file or the env vars set.
argparse reads every arg after the values of an option that takes any number of values as one more value, until the next option. So those lists go first, where the source's other args end them. When nothing from the source follows them and the command line goes on with a subcommand or positional, they go before the first option on the command line instead, if there is one. Where a block that ends with such a list ends is recorded, so that parse_known_args() can check what follows it once every source is in. When an earlier source's list is still followed by a subcommand or positional, this source's args go where that list ends, which ends it.
| Parameters | |
| args | the command line args so far. |
| variable | the args that set options taking any number of values to a list. |
| other | the source's other args. |
| last | the config file key or env var that set the last of those lists, for an error message. |
| variable | (index, key) pairs, updated in place. |
| Returns | |
list | the args with these inserted |
Check whether a command line arg would set a write-out-config-file arg.
| Parameters | |
| arg | a single command line arg. |
| parsers | the parsers that could end up parsing it. |
| Returns | |
bool | whether it names a write-out-config-file arg |
Tries to parse config file path(s) from within command_line_args. Returns a list of opened config files, including files specified on the commandline as well as any default_config_files specified in the constructor that are present on disk.
| Parameters | |
| command | List of all args |
| Returns | |
list[tuple[io.IOBase, str]] | list of (stream, source_label) pairs. The source_label is unique per entry (file path for path entries; "<entry_label>[<index>]" for callable entries), so different entries cannot collapse into a single source key in format_values(). |
Find the option strings that, when already on the command line, mean an env var or config file value for the given action should be dropped.
These are the action's own option strings plus those of every other action in the same mutually exclusive group, mirroring the conflicts argparse checks for. Without the latter, a config file value for one member of a group would clash with a different member given on the command line instead of being overridden by it (see issue #164).
| Parameters | |
| action | the argparse.Action to find overriding option strings for. |
| Returns | |
list[str] | the option strings |
Report args that no arg of this parser took, the way argparse does.
| Parameters | |
| unrecognized | the args left over after parsing. |
Put back the string a value came from where str() can't stand in for it.
Only a value other than a str, int, float, bool or Enum (eg. a dict from type=json.loads, or a list from a type= callable that splits its string) is replaced, and only when it is the very object argparse made for this action from a string in the last parse: a command line or env var value, or a string default or const. So a value set any other way, such as a default that isn't a string, is kept.
| 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 value or list element replaced |
Report an error the way argparse does for its own errors.
With exit_on_error=False, argparse raises an ArgumentError instead of exiting, so errors in config files and env vars do the same.
| Parameters | |
| message | the error message. |
Reject synthesized command line args that set a write-out-config-file arg.
Config file entries and environment variables are turned into command line args and then parsed like any others, so either one's key or its value can end up naming an arg. A write-out-config-file arg overwrites the path it is given and then exits the program, so only the real command line may set one: otherwise whoever controls a config file the program reads could destroy an arbitrary file without the user passing any args at all. (This is also why get_possible_config_keys() keeps these args out of the keys a config file can set.)
These args are checked against every parser reachable from this one, not just the one that looks like it will parse them. Which subcommand runs can't be told from the args: an option's value reads exactly like a subcommand name, and the synthesized args can name a subcommand themselves. So a config file may not name a write-out arg anywhere in the parser tree, which costs an error on a key named after one on a subcommand that wasn't going to run.
| Parameters | |
| synthesized | command line args built from a config file or from environment variables, before they are added to the real ones. |
| source | where they came from, for the error message. |
| parsers | the parsers that could end up parsing them: this parser and every subparser reachable from it (see _subparsers_of()). A subparser is given the args this parser has put together and treats them as its own command line, and argparse parses it into this parser's namespace, so both what a subparser accepts and what it stores matter here. Subparsers that aren't ConfigArgParse parsers are walked through as well, since one of them can hold a subparser that is. |
| Returns | |
bool | whether the args may be used. error() is meant to stop the program, but a program can override exit(), so this says so rather than counting on the call not returning. |
Find the write-out-config-file args the given parsers define.
| Parameters | |
| parsers | the parsers to look in. |
| Returns | |
list | each such arg as an (argparse.ArgumentParser, argparse.Action) pair, since it's the parser an arg belongs to that decides which command line args can set it. |