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 the options to the appropriate values…
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
-hfor help properly.