Search code examples
pythonfileargumentsargparse

Ignore not-passed args


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


Solution

  • 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.