type=dict in argparse.add_argument()

后端 未结 11 702
既然无缘
既然无缘 2020-12-03 07:02

I\'m trying to set up a dictionary as optional argument (using argparse); the following line is what I have so far:

parser.add_argument(\'-i\',\'--image\', t         


        
11条回答
  •  旧巷少年郎
    2020-12-03 07:26

    A minimal example to pass arguments as a dictionary from the command line:

    # file.py
    import argparse
    import json
    parser = argparse.ArgumentParser()
    parser.add_argument("-par", "--parameters",
                        required=False,
                        default=None,
                        type=json.loads
                    )
    args = parser.parse_args()
    print(args.parameters)
    

    and in the terminal you can pass your arguments as a dictionary using a string format:

    python file.py --parameters '{"a":1}'
    

提交回复
热议问题