type=dict in argparse.add_argument()

后端 未结 11 709
既然无缘
既然无缘 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:22

    Here is a another solution since I had to do something similar myself. I use the ast module to convert the dictionary, which is input to the terminal as a string, to a dict. It is very simple.

    Code snippet

    Say the following is called test.py:

    import argparse
    import ast
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--params', '--p', help='dict of params ',type=str)
    
    options = parser.parse_args()
    
    my_dict = options.params
    my_dict = ast.literal_eval(my_dict)
    print(my_dict)
    for k in my_dict:
      print(type(my_dict[k]))
      print(k,my_dict[k])
    

    Then in the terminal/cmd line, you would write:

    Running the code

    python test.py --p '{"name": "Adam", "lr": 0.001, "betas": (0.9, 0.999)}'
    

    Output

    {'name': 'Adam', 'lr': 0.001, 'betas': (0.9, 0.999)}
    
    name Adam
    
    lr 0.001
    
    betas (0.9, 0.999)
    

提交回复
热议问题