python生成yaml文件_Python读取yaml生成菜单

需求:

每个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值