Python读取yaml生成菜单
2018-01-15 00:31
288 查看
需求:
每个location有对应的env, 每个env有对应的infolocation1: dev:bar qa:foo uat:xxx location2: dev:xxx qa:xxx
需要生成菜单,可以选择任意location中的env
Please choose location: 1: location1 2: location2 Enter your choice [1-2] : 1 1: dev 2: qa 3: uat Enter your choice [1-3] : 2 You chosen location1 qa foo
思路及实现:
将配置信息存入配置文件中,在此选用yaml利用python字典及列表的操作获取相应的值。
config.yml
location1: - env: dev info: bar - env: qa info: foo - env: uat info: xxx location2: - env: dev info: xxx - env: qa info: xxx
menu.py
# -*- coding: utf-8 -*- #author: firxiao #date:20180115 #generate a menu from yaml config file. import yaml #读取配置文件 cfg为字典 with open("config.yml", 'r') as ymlfile: cfg = yaml.load(ymlfile) print("Please choose location:") #打印带序号排序过的字典 for i,location in enumerate(sorted(cfg)): print('%d: %s'% (i + 1,location)) #获取字典长度供菜单使用 lr = len(cfg) choice = int(input('Enter your choice [1-%d] : ' % (lr))) while True: if not choice: break # 将选项变为列表并根据输入序号选取 location = list(sorted(cfg))[choice - 1] # 打印字典中key的value for i,d in enumerate(cfg[location]): print('%d: %s'% (i+1,d['env'])) le = len(cfg[location]) choice = int(input('Enter your choice [1-%d] : ' % (le))) # 同理,将选项转换为列表并取出相应的value print('You chosen %s %s %s'% (location,list(cfg[location])[choice - 1]['env'],list(cfg[location])[choice - 1]['info'])) env = list(cfg[location])[choice - 1]['env'] info = list(cfg[location])[choice - 1]['info'] break
相关文章推荐
- python读取csv文件生成系统账号dos命令bat文件
- python读取html中指定元素生成excle文件示例
- C#,读取Xml生成菜单
- 利用Python读取文件名并生成txt文件——以图片文件为例
- python 读取文件生成嵌套列表
- 读取INRIA 说明文件 生成 voc xml python 版本
- c#:Dataset读取XML文件动态生成菜单
- Python读取excel指定列生成指定sql脚本
- python读取csv----python根据IP列表生成百度IP热点图tilemap
- c#从数据库读取数据动态生成树形菜单
- python 读取excel文件生成sql文件实例详解
- python读取excel文件生成sql文件
- python读取html中指定元素生成excle文件示例
- php 从数据库读取数据并生成树型可折叠菜单
- Ajax按需读取数据生成下级菜单
- python读取文件名称生成list的方法
- easyUI( accordion +tree)动态生成导航菜单(数据库读取数据)
- java从数据库读取菜单,递归生成菜单树
- python读取目录下文件并生成日志
- python 读取全国城市aqi数据,差值生成png图片