Argparse: defaults from file

2024/4/15 1:48:04

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?

Answer

Try the following, using dict.update():

import argparse
import configparserconfig = 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'}
https://en.xdnf.cn/q/73222.html

Related Q&A

How can access Uploaded File in Google colab

Im new in python and I use Google Colab . I uploaded a train_data.npy into google Colab and then I want to use it . According to this link How to import and read a shelve or Numpy file in Google Colabo…

__add__ to support addition of different types?

Would be very easy to solve had python been a static programming language that supported overloading. I am making a class called Complex which is a representation of complex numbers (I know python has …

How to open .ndjson file in Python?

I have .ndjson file that has 20GB that I want to open with Python. File is to big so I found a way to split it into 50 peaces with one online tool. This is the tool: https://pinetools.com/split-files N…

loading a dataset in python (numpy) when there are variable spaces delimiting columns

I have a big dataset contains numeric data and in some of its rows there are variable spaces delimiting columns, like:4 5 6 7 8 9 2 3 4When I use this line:dataset=numpy.loadtxt("dataset.txt&q…

how to organise files with python27 app engine webapp2 framework

Ive gone through the getting started tut for python27 and app engine: https://developers.google.com/appengine/docs/python/gettingstartedpython27/By the end of the tut, all the the classes are in the sa…

Keras MSE definition

I stumbled across the definition of mse in Keras and I cant seem to find an explanation.def mean_squared_error(y_true, y_pred):return K.mean(K.square(y_pred - y_true), axis=-1)I was expecting the mean …

How do I adjust the size and aspect ratio of matplotlib radio buttons?

Ive been trying for hours to get the size and aspect ratio of a simple list of radio buttons correct with no success. Initially, import the modules:import matplotlib.pyplot as plt from matplotlib.widge…

App engine NDB: how to access verbose_name of a property

suppose I have this code:class A(ndb.Model):prop = ndb.StringProperty(verbose_name="Something")m = A() m.prop = "a string value"Now of course if I print m.prop, it will output "…

How do I load specific rows from a .txt file in Python?

Say I have a .txt file with many rows and columns of data and a list containing integer values. How would I load the row numbers in the text file which match the integers in the list?To illustrate, sa…

How to check in python if Im in certain range of times of the day?

I want to check in python if the current time is between two endpoints (say, 8:30 a.m. and 3:00 p.m.), irrespective of the actual date. As in, I dont care what the full date is; just the hour. When I c…