Python : Argparse take default value from json file if not passed in command line

66 views Asked by At

I have a script with command-line arguments that I need to modify. I want to make -x, -s, and -e mandatory, while -m should be optional. If -m is not passed, it should take the value from a JSON file. Each -x value will have a separate file with the same name under /opt/abc_m.json. Note that every input of -x will have a file placed under /opt. Invalid -x options will exit the code.

The contents of abc_m.json are as follows

{
  "memory": "'12000",
  "container_vcpus": "2",
  "container_memory": "14336"
}

The argparse code is as follows

parser.add_argument('-x', dest='shops', metavar='SHOP', type=str, nargs='+',
                    help='shop name (eg "abc_m") for which to process')
parser.add_argument('-s', '--start', dest='start', required=False, metavar='START', type=str, default=None,
                    help='Starting  date as in integer in YYYYMMDD format')
parser.add_argument('-e', '--end', dest='end', metavar='END', type=str, required=False, default=None,
                    help='Ending  date as in integer in YYYYMMDD format')
parser.add_argument('-m', '--memory', dest='memory', metavar='MEMORY', type=int, required=False, default=None,
                    help='Memory allocation in MB')

I am not sure is it possible to parse json to get argparse default value

1

There are 1 answers

1
Guy On

You can check the value afterwards and read it if necessary

parser.add_argument('-m', '--memory', dest='memory', metavar='MEMORY', type=int, required=False, default=None, help='Memory allocation in MB')
memory = parser.parse_args().memory

if memory is None:
    with open('abc_m.json') as js:
        memory = int(json.load(js)['memory'])