I'm trying to combine configparser and argparse for a script such that the default values for the various arguments defined by argparse are stored in a config file which is manipulated via configparser. The problem I'm running into is with boolean options. argparse has the store_true
and store_false
actions for these options which automatically create a default and specify what to change to when the option is given. However, since the default is being read in from the config file, I don't know what it is ahead of time in order to use these actions. This would suggest something like:
import argparse,configparser
config = configparser.ConfigParser()
config['DEFAULT']['test'] = 'False'
config.read('testing.cfg')
parser = argparse.ArgumentParser()
if config.getboolean('DEFAULT','test'):
parser.add_argument('-t',action='store_false', dest='test')
else:
parser.add_argument('-t',action='store_true', dest='test')
args = parser.parse_args()
print(args.test)
However, I don't like the idea of having a parser.addargument
statements inside a conditional (especially cumbersome the more of these options that I have). What I would prefer is a something like:
parser.add_argument('-t',action='toggle_boolean',dest='test',default=config.getboolean('DEFAULT','test'))
In this instance the toggle_boolean
action would switch the state of boolean, whatever it happens to be, when the argument is given. The problem is that said action (toggle_boolean
) doesn't exist. How would I go about defining such an action, or is there a better way of doing this?