# 练习82:定义函数 read_config_from_yaml(yaml_path,key,sub_key),
# 实现功能读取yaml文件中配置数据。
# 例如:read_config_from_yaml('testyaml.yaml') 返回yaml文件中所有内容
# read_config_from_yaml('testyaml.yaml','mysql') 返回testyaml.yaml文件中mysql的值
# read_config_from_yaml('testyaml.yaml','mysql','user') 返回user的值root
import yaml
def read_config_from_yaml(yaml_path,key=None,sub_key=None):
with open(yaml_path,'r',encoding='utf-8') as f:
r = yaml.load(stream=f,Loader=yaml.FullLoader)
if key is None and sub_key is None:
return r
elif key is not None and sub_key is None:
return r[key]
else:
return r[key][sub_key]
if __name__ == "__main__":
yaml_path = r'D:\Lim\Python\pythonstudy\day7\test.yaml'
print(read_config_from_yaml(yaml_path))
print()
print(read_config_from_yaml(yaml_path,'mysql'))
print()
print(read_config_from_yaml(yaml_path,'mysql','host'))