安装python-yaml
sudo apt-get install python-yaml
假设data.yml内容如下
1 2 3 4 5 6 7 |
config1: epoch: 300 name: "CNN" tag: - testconf - testyml |
python解析代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
#encoding=utf-8 import os import argparse import yaml def resolve_yml(path): with open(path, 'r') as f: try: configs = yaml.safe_load(f.read()) except yaml.YAMLError: raise Exception('Error parsing YAML file:' + path) for config_name in configs: # config_name 是字符串类型 # config 是字典类型 config = configs[config_name] if 'epoch' in config: print 'epoch is %d' % config['epoch'] if 'name' in config: print 'name is ' + config['name'] if 'tag' in config: tags = config['tag'] # tags是一个列表 for tag in tags: print tag def parse_args(): parser = argparse.ArgumentParser(description='to import chals and matches.') parser.add_argument('path',help='path to yml file') args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() path = args.path try: # 判断文件是否存在 if not os.path.isfile(path): raise Exception("%s file does not exist" % path) except Exception, e: print('Exception:' + str(e)) resolve_yml(path) |
运行
python yml.py data.yml
运行结果
1 2 3 4 5 6 7 |
''' 运行结果 epoch is 300 name is CNN testconf testyml ''' |