I have a Python script which takes a lot of arguments.
I currently use a configuration.ini
file (read using configparser
), but would like to allow the user to override specific arguments using command line.
If I'd only have had two arguments I'd have used something like:
if not arg1:
arg1 = config[section]['arg1']
But I don't want to do that for 30 arguments.
Any easy way to take optional arguments from cmd line, and default to the config
file?
You can use a ChainMap from the
collections
module.From the doc:
So, you could create
config
dict containing the key-value pairs from your config file,cmd_line_args
dict containing the ones given on the command lineThen, create a ChainMap:
When you access
combined['arg1']
, arg1 will first be looked up in thecmd_line_args
dict, and if it isn't found there,config[arg1]
will be returned. You can chain as many dicts as you wish, which lets you combine as many levels of defaults as you wish.Try the following, using dict.update():
With this example of ini file:
and
result
would contain: