YAML是“YAML Is not markup language”的缩写形式,是一种数据序列化语言;其文件扩展名为 ~.yml;
语法参考:https://www.yiibai.com/yaml/
使用
#
作为注释开始,YAML中只有行注释。
1)配置大小写敏感;
2)使用缩进代表层级关系;
3)缩进只能使用空格,不能使用TAB,不要求空格个数,只需要相同层级左对齐(一般2个或4个空格);
1)对象:格式为key: value,冒号后面要加一个空格:
key: value
2)数组:完整配置:
# 这是一个yaml配置文件
# 常规对象语法
mysql_A:
host : 77.77.77.77
port : 5432
dbname : db_name_a
user : user_name
passwd : password_a
# 流式(flow)语法表示对象
oracle_B: {host : 99.99.99.99, port : 1521, dbname : db_name_b, user : user_name, passwd : password_b}
# 配置环境信息和输出对象
target_db:
mainFlag: True
dbType: oracle
host: xx.xx.xx.xx
port: xxxx
dbsid: xxxx
username: xxx
password: xxx
output_object:
target_list:
name: t_parse_object_frompdm
stru: [object_name, object_type, object_comments, object_ddl, creationdate, creator, modificationdate, modifier, sc_sj]
target_columns:
name: t_parse_columns_frompdm
stru: [object_name, column_name, column_id, uk_flag, data_type, data_length, data_precision, data_scale, nullable, column_comments, sc_sj]
类库简介:https://pyyaml.org/wiki/PyYAMLDocumentation
Python解析
yaml文件
依赖pyyaml
库,对应的模块为yaml
;
模块安装:
pip install pyyaml
pip show pyyaml
# coding=utf-8
"""
@DevTool : PyCharm
@Author : xxx
@DateTime : 2022/5/20 11:28
@FileName : parseYaml_demo.py
"""
import os.path
import yaml
pwd_path = os.path.abspath(".")
file_path = os.path.join(pwd_path, "dbEnvConf.yaml")
with open(file_path,mode="r",encoding="utf-8") as f:
yamlConf = yaml.load(f.read(), Loader=yaml.FullLoader)
print(yamlConf)
输出结果
D:\SoftWare\Python\python.exe E:/PythonProject/FileOperTest/parseYaml_demo.py
{'mysql_A': {'host': '77.77.77.77', 'port': 5432, 'dbname': 'db_name_a', 'user': 'user_name', 'passwd': 'password_a'}, 'oracle_B': {'host': '99.99.99.99', 'port': 1521, 'dbname': 'db_name_b', 'user': 'user_name', 'passwd': 'password_b'}}
Process finished with exit code 0
yamlConf = yaml.full_load(f.read())
yamlConf = yaml.safe_load(f.read())
yamlConf = yaml.load(f.read(), Loader=yaml.CLoader)
说明:以上 几种方式都可以实现 yaml 文件到 dict 格式对象的转换和加载;
target_list_name = yamlConf["output_object"]["target_list"]["name"]
target_list_stru = yamlConf["output_object"]["target_list"]["stru"]