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...
Update: This answer still has issues; for example, it cannot handle
required
arguments, and requires an awkward config syntax. Instead, ConfigArgParse seems to be exactly what this question asks for, and is a transparent, drop-in replacement.One issue with the current is that it will not error if the arguments in the config file are invalid. Here's a version with a different downside: you'll need to include the
--
or-
prefix in the keys.Here's the python code (Gist link with MIT license):
Here's an example of a config file:
Now, running
However, if our config file has an error:
Running the script will produce an error, as desired:
The main downside is that this uses
parser.parse_args
somewhat hackily in order to obtain the error checking from ArgumentParser, but I am not aware of any alternatives to this.