您的位置:首页 > 编程语言 > Python开发

Python读取yaml生成菜单

2018-01-15 00:31 288 查看

需求:

每个location有对应的env, 每个env有对应的info

location1: 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 menu