0

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 ?

newstudent
  • 402
  • 6
  • 19
  • The consensus seems to be providing positive and negative switches, see https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse, https://stackoverflow.com/questions/9234258/in-python-argparse-is-it-possible-to-have-paired-no-something-something-arg, perhaps https://stackoverflow.com/questions/34735831/python-argparse-toggle-no-toggle-flag – tevemadar Aug 05 '22 at 07:41
  • https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.getboolean – jonrsharpe Aug 05 '22 at 07:42
  • The old question doesn't provide answer for the current post. But still this post has been closed. – newstudent Aug 05 '22 at 07:53

0 Answers0