Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse: defaults from file

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?

like image 364
shayelk Avatar asked Jan 31 '18 09:01

shayelk


1 Answers

Try the following, using dict.update():

import argparse
import configparser

config = configparser.ConfigParser()
config.read('config.ini')
defaults = config['default']

parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='arg1')
parser.add_argument('-b', dest='arg2')
parser.add_argument('-c', dest='arg3')
args = vars(parser.parse_args())

result = dict(defaults)
result.update({k: v for k, v in args.items() if v is not None})  # Update if v is not None

With this example of ini file:

[default]
arg1=val1
arg2=val2
arg3=val3

and

python myargparser.py -a "test"

result would contain:

{'arg1': 'test', 'arg2': 'val2', 'arg3': 'val3'}
like image 71
ettanany Avatar answered Oct 24 '22 12:10

ettanany