青岛制作网站企业,企业搭建自己的网站,网站建设塞西,wordpress 搜索tagmarkdown 的配置使用 Yaml —— Yet Another Markup Language #xff1a;另一种标记语言。
简介
YAML 是专门用来写配置文件的语言#xff0c;非常简洁和强大#xff0c;远比 JSON 格式方便。 YAML在python语言中有PyYAML安装包。 YAML 语言#xff08;发音 /ˈjməl/ 另一种标记语言。
简介
YAML 是专门用来写配置文件的语言非常简洁和强大远比 JSON 格式方便。 YAML在python语言中有PyYAML安装包。 YAML 语言发音 /ˈjæməl/ 的设计目标就是方便人类读写。它实质上是一种通用的数据串行化格式。
它的基本语法规则如下
大小写敏感使用缩进表示层级关系缩进时不允许使用Tab键只允许使用空格。缩进的空格数目不重要只要相同层级的元素左侧对齐即可# 表示注释从这个字符一直到行尾都会被解析器忽略这个和python的注释一样
YAML 支持的数据结构有三种
对象键值对的集合。键值对用冒号 “:” 结构表示冒号与值之间需用空格分隔数组一组按次序排列的值。数组前加有 “-” 符号符号与值之间需用空格分隔纯量scalars单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期
python 操作 YAML 文件的模块 pyyaml
pyyaml 库不支持读取文档中嵌入的yaml。这是一个提取yaml文本的实用程序函数因此可以先提取 yaml 的数据对其进行解析
1. 安装
pip install pyyaml2. yaml 文件示例
apiVersion: apps/v1
kind: Deployment
metadata:name: linux-node02namespace: yaml-demo
spec:replicas: 1selector:matchLabels:app: podinfotemplate:metadata:labels:app: podinfospec:containers:- image: quay.io/stefanprodan/podinfo:0.3.0name: podinfodports:- containerPort: 98983. 读取 yaml 文件
import yaml
import osyamlPath config.yaml
with open(yamlPath,r,encodingutf-8) as f:# print(f.read())result f.read()x yaml.load(result,Loaderyaml.FullLoader)print(type(x))print(x)class dict
{apiVersion: apps/v1, kind: Deployment, metadata: {name: linux-node02, namespace: yaml-demo}, spec: {replicas: 1, selector: {matchLabels: {app: podinfo}}, template: {metadata: {labels: {app: podinfo}}, spec: {containers: [{image: quay.io/stefanprodan/podinfo:0.3.0, name: podinfod, ports: [{containerPort: 9898}]}]}}}} 备注如果报警告 YAMLLoadWarning: calling yaml.load() without Loader… is deprecated 修改代码如下
import yaml
from Common.dir_config import *fs open(os.path.join(caps_dir, data.yaml),encodingUTF-8)
datas yaml.load(fs,Loaderyaml.FullLoader) #添加后就不警告了3.1 分段yaml文件中多个文档
多个文档在一个yaml文件使用 — 分隔方式来分段示例如下
---
animal1: dog
age: 2
---
animal2: cat
age: 3python脚本读取一个yaml文件中多个文档方法
python获取yaml数据时需使用 load_all() 函数来解析全部的文档再从中读取对象中的数据load_all() 返回一个生成器
def get_yaml_load_all(yaml_file):# 打开yaml文件file open(yaml_file, r, encodingutf-8)file_data file.read()file.close()all_data yaml.load_all(file_data)for data in all_data:print(data)current_path os.path.abspath(.)
yaml_path os.path.join(current_path, config.yaml)
get_yaml_load_all(yaml_path)
结果
{animal1: dog, age: 2}
{animal2: cat, age: 3}4. 修改 yaml 文件
import yaml
import osyamlPath config.yaml
# 修改yaml配置
with open(yamlPath,r,encodingutf-8) as f:# print(f.read())result f.read()x yaml.load(result,Loaderyaml.FullLoader)# 修改x[metadata][name] linux-node02with open(yamlPath,w,encodingutf-8) as w_f:# sort_keysFalse写入yaml的数据则不会排序后写入# allow_unicode 防止中文转义yaml.dump(x, w_f, allow_unicodeTrue, sort_keysFalse)