I have the below script for using argparse and wish to use configparse effectively.
#main.py
import argparse, configparser
parser = argparse.ArgumentParser()
parser.add_argument(
"-c",
"--config_file",
type=str,
help='Config file')
parser.add_argument(
'-S',
'--testcase',
dest='scp',
choices=['foo1','foo2'],
type=str,
help='Choose of the component',
default=None)
parser.add_argument(
'--displayone',
dest='disphone',
action='store_true',
default=None)
parser.add_argument(
'--displaytwo',
dest='disphtwo',
action='store_true',
default=None)
args = parser.parse_args()
if args.config_file:
config = configparser.ConfigParser()
config.read(args.config_file)
defaults = {}
defaults.update(dict(config.items("DEF")))
parser.set_defaults(**defaults)
display = {}
display.update(dict(config.items("DISPLAY")))
parser.set_defaults(**display)
if args.scp == 'foo1':
print("This is a foo config test")
if args.disphone:
print("This is displayone foo1 test")
if args.disphtwo:
print("This is displaytwo foo1 test")
Using command line arguments:
python3 main.py --testcase foo1 --displayone
I get exactly what I need. However as I wish to use a config
file, and I want a boolean switch for key-value pairs disphone
and disphtwo
such that --displayone
or --displaytwo
task is performed accordingly as above.
Below is an example input.ini
config file.
[DEF] #default
scp = foo1
disphone = FALSE
disphtwo = FALSE
[DISPLAY]
disphone = TRUE
disptwo = FALSE
I tried with disphone =
(empty key value) to switch off the argument, but I don't prefer it. TRUE
or FALSE
would be a better option for the user. Can someone suggest how to work through this ?