Extends argparse.ArgumentParser to make it able to take in values from a configuration file.
Beyond the added functionality it doesn't not modify the behaviour of argparse.ArgumentParser and can thus be used as a drop in replacement.
You may want to provide values either to the CLI or by configuration file. And you don't want to check yourself if each value not provided to the CLI is present in the configuration file. And you also don't want the CLI to shout an error because it hasn't been provided an option when it is present in the configuration file.
It inserts values from the configuration files before CLI provided values into sys.argv. The last provided value overrules the previous one. Thus if you provide a value which is present in the configuration file, the configuration file value won't be used.
- Provide the configuration as a dict to the constructor:
with open("application.yml", "r") as config_file:
config = yaml.load(config_file)
parser = ConfArgParser(description="Cli prototype", config=config)
- Link the corresponding item to the option:
parser.add_argument("--host", required=True, type=str, conf_key="mysql.host")
parser.add_argument("--user", required=True, type=str, conf_key="mysql.user")
- If a value is present in the configuration file and is linked to an option, it is added to sys.argv:
args = parser.parse_args()
print(args)
Assuming the configuration file defines mysql.host: localhost and mysql.user: me the call cli --host 127.0.0.1
becomes cli --host localhost --user me --host 127.0.0.1
which is equivalent to cli --user me --host 127.0.0.1
.
And it outputs: Namespace(host='127.0.0.1', user='me')