Home > Back-end >  Ignore not-passed args
Ignore not-passed args

Time:04-01

I am trying to generate some JSONs based on passed arguments, but everytime I run the script it generates all JSONs, not only those I specify in the CLI

import json
import argparse
listOfJSONS = {
    "JSON1" : "path",
    "JSON2" : "path",
    ...
    }

if __name__ == "__main__":
    parser.add_argument(
            "--JSON1",
            action='store_true',
            default=False,
            help="Creates one JSON",
        )

    parser.add_argument(
            "--JSON2",
            action='store_true',
            default=False,
            help="Creates different JSON",
        )
    # repeat .add_argument() for all JSONS in the dict
    args = parser.parse_args()
        for arg in vars(args):
            if arg in listOfJSONS .keys():
                with open(listOfJSONS.get(arg), "w", encoding="utf-8") as json_file:
                json_file.write(json_string)

But when I run

python ./JSONgenerator.py --JSON1 --JSON2

It creates all JSONs specified in the listOfJSONS, not only the two I specified. Thank you very much for any help

EDIT: I also tried to use sys.argv([1:]) in args = parser.parse_args(sys.argv[1:]) with no success

CodePudding user response:

for arg, argbool in args._get_kwargs():
    if argbool and arg in listOfJSONS.keys():
        with open(listOfJSONS.get(arg), "w", encoding="utf-8") as json_file:
            json_file.write(json_string)

This should work.

CodePudding user response:

It seems you could simplify this quite a bit by just using one argument with nargs. Here is an example:

import argparse

JSON_PATHS = {
    "JSON1": "path/json1",
    "JSON2": "path/json2",
}

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("files", nargs=" ")
    args = parser.parse_args()
    for f in args.files:
        print(JSON_PATHS.get(f))
➜ ./main.py JSON1 JSON2

outputs:

path/json1
path/json2
  • Related