Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write list of string to yaml file in the format of github actions using python

The python yaml package (version 5.1.2) is able to load the following file correctly, even though the list is not written with leading -

xx: [x1, x2]
yy: [y1, y2, y3]

The loading code is as follows

import yaml

with open('some file') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)

This format is used in github actions config yaml files. For example,

on: [push, pull_request]

jobs:
  build:

    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: [2.7, 3.5, 3.6, 3.7, 3.8]
        os: [ubuntu-16.04, ubuntu-18.04]
        node: [6, 8, 10]

But when I write data to file using yaml.dump(data, f), it takes the - convention, i.e.,

xx:
- x1
- x2
yy:
- y1
- y2
- y3

Is there a way to force it into the github-actions-like format?

I was told about default_flow_style, but it doesn't give exactly what I want.

yaml.dump({"A":[1,2,3],"B":[4,5,6]},default_flow_style=True)

The output is '{A: [1, 2, 3], B: [4, 5, 6]}\n'

like image 594
nos Avatar asked Sep 12 '25 17:09

nos


1 Answers

As pointed out by @Tsyvarev my desired behavior can be triggered by

yaml.dump({"A":[1,2,3],"B":[4,5,6]}, default_flow_style=None)

The official documentation doesn't seem to define this None behavior though:

By default, PyYAML chooses the style of a collection depending on whether it has nested collections. If a collection has nested collections, it will be assigned the block style. Otherwise it will have the flow style.

If you want collections to be always serialized in the block style, set the parameter default_flow_style of dump() to False.

like image 57
nos Avatar answered Sep 14 '25 08:09

nos