python - 在 ruamel.yaml 中,如何使用文字字符串“null”发出 ScalarEvent?
问题描述
我正在使用 ruamel.yaml 发出一系列事件来创建自定义 YAML 文件格式混合流样式。
我发现自己无法发出值为“null”的 ScalarEvent,因此它在 YAML 文件中显示为字符串“null”,而不是 YAML 关键字 null。
以代码形式,如果我尝试
dumper = yaml.Dumper(out_file, width=200)
param = 'field'
param_value = 'null'
dumper.emit(yaml.MappingStartEvent(anchor=None, tag=None, implicit=True, flow_style=True))
dumper.emit(yaml.ScalarEvent(anchor=None, tag=None, implicit=(True, True), value=param))
dumper.emit(yaml.ScalarEvent(anchor=None, tag=None, implicit=(True, True), value=param_value))
dumper.emit(yaml.MappingEndEvent())
我明白了
field: null
而我想看看
field: 'null'
解决方案
您的代码不完整,但是由于您设置flow_style=True
了映射事件,因此您没有获得显示的代码,也永远不会获得您想要的输出。
如果您想走这条路,请查看代码中唯一ruamel.yaml
发出ScalarNode
. 它在serializer.py
:
self.emitter.emit(
ScalarEvent(
alias,
node.tag,
implicit,
node.value,
style=node.style,
comment=node.comment,
)
)
从那里你会发现你需要添加style
参数。进一步挖掘将显示这应该是一个单字符串,在您的情况下是单引号(“ '
”),以强制使用单引号标量。
import sys
import ruamel.yaml as yaml
dumper = yaml.Dumper(sys.stdout, width=200)
param = 'field'
param_value = 'null'
dumper.emit(yaml.StreamStartEvent())
dumper.emit(yaml.DocumentStartEvent())
# !!!! changed flow_style in the next line
dumper.emit(yaml.MappingStartEvent(anchor=None, tag=None, implicit=True, flow_style=False))
dumper.emit(yaml.ScalarEvent(anchor=None, tag=None, implicit=(True, True), value=param))
# added style= in next line
dumper.emit(yaml.ScalarEvent(anchor=None, tag=None, implicit=(True, True), style="'", value=param_value))
dumper.emit(yaml.MappingEndEvent())
dumper.emit(yaml.DocumentEndEvent())
dumper.emit(yaml.StreamEndEvent())
这给了你想要的:
field: 'null'
但是,我认为您正在使您的生活变得比必要的更加困难。ruamel.yaml
确实在往返过程中保留了流式,并且您创建了一个功能数据结构并转储它,而不是恢复到使用事件驱动转储器:
import sys
import ruamel.yaml
yaml_str = """\
a:
- field: 'null'
x: y
- {field: 'null', x: y}
"""
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
for i in range(2):
data["a"].append(ruamel.yaml.comments.CommentedMap([("a", "b"), ("c", "d")]))
data["a"][-1].fa.set_flow_style()
yaml.dump(data, sys.stdout)
这给出了:
a:
- field: 'null'
x: y
- {field: 'null', x: y}
- a: b
c: d
- {a: b, c: d}
推荐阅读
- android - 在android中触摸屏幕任何部分之外时隐藏软键盘的解决方案
- reactjs - 你如何处理 NextJS 应用程序中的公共和私有路由?
- mysql - 如何从 findOne 函数 MySQL 返回布尔值
- amazon-web-services - PySpark 中的 Hello World 程序 - EMR
- r - 有没有办法在 R 中将 str_detect 与 group_by 一起使用?
- bash - 如何搜索文件中两个单词之间的内容
- php - 我如何加强 Wordpress 的自定义 Facebook 登录的安全性?
- azure-active-directory - Azure Runbook - [AzureAD] Get-AzureADUser -All
- java - 春季启动中的 NullPointerException
- java - 在密码验证例程中使用 if 语句查询 do while 循环