I have a Python application which needs quite a few (~30) configuration parameters. Up to now, I used the OptionParser class to define default values in the app itself, with the possibility to change individual parameters at the command line when invoking the application.
Now I would like to use 'proper' configuration files, for example from the ConfigParser class. At the same time, users should still be able to change individual parameters at the command line.
I was wondering if there is any way to combine the two steps, e.g. use optparse (or the newer argparse) to handle command line options, but reading the default values from a config file in ConfigParse syntax.
Any ideas how to do this in an easy way? I don't really fancy manually invoking ConfigParse, and then manually setting all defaults of all optinos to the appropriate values...
I can't say it's the best way, but I have an OptionParser class that I made that does just that - acts like optparse.OptionParser with defaults coming from a config file section. You can have it...
Feel free to browse the source. Tests are in a sibling directory.
Try to this way
Use it:
And create example config:
Check out ConfigArgParse - its a new PyPI package (open source) that serves as a drop in replacement for argparse with added support for config files and environment variables.
fromfile_prefix_chars
Maybe not the perfect API, but worth knowing about.
main.py
:Then:
Documentation: https://docs.python.org/3.6/library/argparse.html#fromfile-prefix-chars
Tested on Python 3.6.5, Ubuntu 18.04.
I'm using ConfigParser and argparse with subcommands to handle such tasks. The important line in the code below is:
This will set the defaults of the subcommand (from argparse) to the values in the section of the config file.
A more complete example is below:
I just discovered you can do this with
argparse.ArgumentParser.parse_known_args()
. Start by usingparse_known_args()
to parse a configuration file from the commandline, then read it with ConfigParser and set the defaults, and then parse the rest of the options withparse_args()
. This will allow you to have a default value, override that with a configuration file and then override that with a commandline option. E.g.:Default with no user input:
Default from configuration file:
Default from configuration file, overridden by commandline:
argprase-partial.py follows. It is slightly complicated to handle
-h
for help properly.