python修改yaml文件

在修改gitlab上工程代码后,重新生成一个分支后,再次触发pipeline,但是由于.gitlab-ci.yml文件中配置了only,导致新生成的分支无法触发pipeline,最先想到的是对.gitlab-ci.yml文件当作普通文件处理,这样对于文件的解析要求比较高,后查到有现成的yaml文件解析库,果断使用之。

开始前首先安装yaml库

1
pip install pyyaml

在需要的地方引入即可

1
import yaml

读取yaml文件

  1. 和普通的文件读取一样,首先需要获取文件的对象
  2. 使用yaml.load(fp) 获取文件中的内容,返回格式为字典
    1
    2
    3
    4
    5
    6
    import yaml
    dict_data = {}
    with open("log/test.yml") as f:
    # 返回字典格式的数据
    dict_data = yaml.load(f, Loader=yaml.FullLoader)
    print(dict_data)
    yaml文件内容如下
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    stages:
    - prepare
    - build
    # - test
    # - deploy
    prepare:
    stage: prepare
    script:
    - med prepare -n prepare

    build:
    stage: build
    script:
    - med build -n release
    输入如下
    1
    {'stages': ['prepare', 'build'], 'prepare': {'stage': 'prepare', 'script': ['med prepare -n prepare']}, 'build': {'stage': 'build', 'script': ['med build -n release']}}
    可以看到yaml文件中的一个文本块的key对应字典中的key值,对于使用 -标识的内容,在字典中会以数组的形式存在

load文件的几种模式

  • BaseLoader 载入大部分的基础YAML
  • SafeLoader 载入YAML的子集,推荐在不可信的输入时使用
  • FullLoader 这是默认的载入方式,载入全部YAML
  • UnsafeLoader 老版本的载入方式

load文件时若不传入Loader,则会出现如下错误

YAMLLoadWarning: calling yaml.load() without Loader=… is deprecated,as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.

写入yaml文件

yaml库支持将字典格式的数据写入到yml文件中

1
2
3
dict_data = {'stages': ['prepare', 'build'], 'prepare': {'stage': 'prepare', 'script': ['med prepare -n prepare']}, 'build': {'stage': 'build', 'script': ['med build -n release']}}
with open("log/test2.yml", "w") as f:
yaml.dump(dict_data, f)

可以看到生成文件test2.yml

注意

  1. 从test.yml文件中读出的内容,再写入到yaml文件中时,文件格式已发生变化,要想保持读出的文件格式无变化,可以使用ruamel.yaml,将读出文件的内容存放到了OrderedDict中
    1
    pip install ruamel.yaml
    实例
    1
    2
    3
    4
    5
    6
    7
    8
    from ruamel import yaml
    y = ""
    with open("log/test.yml") as f:
    y = yaml.load(f, Loader=yaml.RoundTripLoader)
    print(y)
    with open("log/test2.yml", "w", encoding="utf-8") as f:
    yaml.dump(y, f, Dumper=yaml.RoundTripDumper)
    `
  2. 若原yaml文件中包含数组和字典对象,则读出文件后再写入时会出现异常,暂无找到合适的解决方法
投食