Python uses docopt parse json parameter file

1. Background

In depth study of the task usually requires more complex parameters and input and output configurations, such as the need different training data, different models, different log file write output to different output folder to avoid confusion

Commonly used parser.add () method is very occupy code space, and can not be changed by the input and output configuration file only through the command-line parameter changes.

docopt library provides a very elegant command line parsing tool, introduced here only parameter which parses files

2. Install

pip install docopt
import docopt
import json

  

3. Use

docopt consists of two parts, the first part is partially resolved by "" "" - "" (double quote some similar annotation shown), this part is essential.

"""
Usage: train <json_file>
"""

Command analysis portion of the above is very simple, should enter:

python  test.py  config.json

The second part is the main function:

if __name__ == "__main__":
    args = docopt.docopt(__doc__)
    args = json.load(open(args["<json_file>"]))
    print('==>Params')
    for key in args.keys():
        print('\t{}:{}\n'.format(key,args[key]))
    train(args) 

I will config.json to:

{
  "dataset":        "human_science",
  "length":         1000,
  "model":          "CNN",
  "log_dir":        "./logs/",
  "output_dir":     "./output/",
  "output_prefix":  "human_science_CNN",

  "lr":0.01
}

Command line output should be:

 

The successful argument to train () function

 

Guess you like

Origin www.cnblogs.com/siyuan1998/p/11312169.html