Python argparse dict arg

前端 未结 9 1687
不知归路
不知归路 2021-02-01 04:31

I want to receive a dict(str -> str) argument from the command line. Does argparse.ArgumentParser provide it? Or any other library?

For the

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 04:34

    There is a simple solution in Python 3.6 if you're simply trying to convert argparse input to a dictionary. An example is as follows:

    import argparse 
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input', help='the path to the input file')
    parser.add_argument('-o', '--output', help='the path to the output file')
    args = parser.parse_args()
    
    arguments = dict(args._get_kwargs())
    
    for k, v in arguments.items():
        print(k, v) 
    

    Given command line input such as python3 script_name.py --input 'input.txt' --output 'output.txt' the code would output to terminal:

    input input.txt
    output output.txt
    

提交回复
热议问题