使用制表符缩进的 YAML 配置 [英] Using a configuration of YAML which is tab indented

查看:32
本文介绍了使用制表符缩进的 YAML 配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个单元测试,我发现了一个使用制表符缩进编写 YAML 配置的工具,但是当我尝试使用 yaml.load(file_object) 读取它时,我收到一条错误消息:

I was writing a unit test, and I discovered a tool that writes YAML configuration with tab indention, but when I tried to read it using yaml.load(file_object) I get an error saying:

(<unknown>): found character that cannot start any token while scanning for the next token at line 2 column 1

或使用我在终端中看到的工具:

or with the tool I see in terminal:

while scanning for the next token
found character '\t' that cannot start any token
  in "/user/config/settings", line 2, column 1

推荐答案

虽然制表符在 YAML 中有效,但它们不能用于缩进,在当前版本中都没有(1.2,也不在较旧的 1.1,或1.0)

Although tab characters are valid in YAML, they cannot be used in indentation, in neither the current version (1.2, nor in the older 1.1, or 1.0)

意味着不能在行首出现制表符,如下所示示例显示

That does not imply a tab cannot occur at the start of line, as the following example shows

import sys
import ruamel.yaml

yaml_str = """\
'xxx
\tyyy'
"""

yaml = ruamel.yaml.YAML()
yaml.explicit_start = True
data = yaml.load(yaml_str)
print(data)

运行没有错误并给出:

xxx yyy

如果您从 yaml_str 中删除单引号,您将得到你得到的错误(在第 2 行,第 1 列),因为解析器必须考虑 yyy 是否开始一个新的令牌(同时扫描单个引用标量它不这样做).

if you remove the single quotes from the yaml_str, you will however get the error that you got (on line 2, column 1), because the parser has to consider if yyy starts a new token (while scanning the single quoted scalar it doesn't do that).

没有看到实际的 YAML,很难断言,但是可能你的工具是罪魁祸首.你可能会逃脱更换标签:

Without seeing the actual YAML, it is difficult to say defitively, but probalby your tool is to blame. You might get away with replacing the tabs:

with open('yourfile.yaml') as fp:
    data = yaml.load(fp.read().replace('\t', ' '))

这篇关于使用制表符缩进的 YAML 配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆