Yaml 无法转储为";纯粹的;亚马尔

Yaml 无法转储为";纯粹的;亚马尔,yaml,ruamel.yaml,Yaml,Ruamel.yaml,ruamel.yaml==0.15.37 Python 3.6.2::Continuum Analytics,Inc 当前代码: from ruamel.yaml import YAML import sys yaml = YAML() kube_context = yaml.load(''' apiVersion: v1 clusters: [] contexts: [] current-context: '' kind: Config pr

ruamel.yaml==0.15.37
Python 3.6.2::Continuum Analytics,Inc

当前代码:

from ruamel.yaml import YAML
import sys


yaml = YAML()
kube_context = yaml.load('''
    apiVersion: v1
    clusters: []
    contexts: []
    current-context: ''
    kind: Config
    preferences: {}
    users: []
''')
kube_context['users'].append({'name': '{username}/{cluster}'.format(username='test', cluster='test'), 'user': {'token': 'test'}})
kube_context['clusters'].append({'name': 'test', 'cluster': {'server': 'URL:443'}})
kube_context['contexts'].append({'name': 'test', 'context': {'user': 'test', 'cluster': 'test'}})

yaml.dump(kube_context, sys.stdout)
My
yaml.dump()
正在生成包含列表和dict对象的输出,而不是完全展开

电流输出:

apiVersion: v1
clusters: [{name: test, cluster: {server: URL:443}}]
contexts: [{name: test, context: {user: test, cluster: test}}]
current-context: ''
kind: Config
preferences: {}
users: [{name: test/test, user: {token: test}}]
要使输出完全展开,我需要做什么

预期产出:

apiVersion: v1
clusters: 
  - name: test
    cluster: 
      server: URL:443
contexts: 
  - name: test
    context:
      user: test
      cluster: test
current-context: ''
kind: Config
preferences: {}
users: 
  - name: test/test
    user: 
      token: test

输出为“纯”YAML。您希望节点以块样式(基于缩进)显示,而不是以当前的流样式([]{})显示。以下是如何做到这一点:

yaml = YAML(typ="safe")
yaml.default_flow_style = False

(注意Athon对下面
类型的评论;您需要将其设置为
safe
safe
,以便RoundTripLoader不会设置空序列的样式)

ruamel.yaml
,当使用默认的
yaml()
yaml(typ='rt'))
将保留序列和映射的-或样式。无法使块样式为空序列或空映射,因此加载时,
[]
{}
将标记为流样式

流样式只能包含流样式(而块样式可以包含块样式或流样式)():

YAML允许将流节点嵌入到块集合中(但反之亦然)

因此,在(流样式)列表/序列中插入的dict/映射数据也将表示为流样式

如果您希望所有内容都是块样式(您称之为“扩展”模式),可以通过调用
.fa
属性上的
.set\u block\u style()
方法来显式设置(该方法仅在集合上可用,因此
try
/
除外):

这使得:

apiVersion: v1
clusters:
- name: test
  cluster:
    server: URL:443
contexts:
- name: test
  context:
    user: test
    cluster: test
current-context: ''
kind: Config
preferences: {}
users:
- name: test/test
  user:
    token: test

请注意,无需在默认往返模式下设置
yaml.default\u flow\u style=False
;尽管已为键
首选项的值设置了块样式
,但它表示为流样式,因为没有其他方式表示空映射。

这适用于所有
类型
“模式”除了OP使用的默认(
typ='rt')模式外,还设置了
.default\u flow\u style=False`(作为设置的一部分),并适用于块样式集合下新添加的叶集合,但不适用于(空)下的叶集合OP加载的流样式集合,以及保留样式的流样式集合。有人可能认为不应在空集合上设置样式,因为无法使块样式为空映射或序列。
apiVersion: v1
clusters:
- name: test
  cluster:
    server: URL:443
contexts:
- name: test
  context:
    user: test
    cluster: test
current-context: ''
kind: Config
preferences: {}
users:
- name: test/test
  user:
    token: test