type=dict in argparse.add_argument()

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

    Combining the type= piece from @Edd and the ast.literal.eval piece from @Bradley yields the most direct solution, IMO. It allows direct retrieval of the argval and even takes a (quoted) default value for the dict:

    Code snippet

    parser.add_argument('--params', '--p', help='dict of params ', type=ast.literal.eval, default="{'name': 'adam'}")
    args = parser.parse_args()
    

    Running the Code

    python test.py --p "{'town': 'union'}"
    

    note the quotes on the dict value. This quoting works on Windows and Linux (tested with [t]csh).

    Retrieving the Argval

    dict=args.params
    

提交回复
热议问题