【问题标题】:Why are PyYAML and ruamel.yaml escaping special characters when single quoted?为什么 PyYAML 和 ruamel.yaml 在单引号时转义特殊字符?
【发布时间】:2016-11-07 06:59:37
【问题描述】:

我有一个 YAML 文件,想限制某个字段不包含空格。

这是一个演示我尝试的脚本:

test.py

#!/usr/bin/env python3

import os
from ruamel import yaml

def read_conf(path_to_config):
    if os.path.exists(path_to_config):
        conf = open(path_to_config).read()
        return yaml.load(conf)
    return None

if __name__ == "__main__":
    settings = read_conf("hello.yaml")
    print("type of name: {0}, repr of name: {1}".format(type(
             settings['foo']['name']), repr(settings['foo']['name'])))
    if any(c.isspace() for c in settings['foo']['name']):
        raise Exception("No whitespace allowed in name!")

这是我的第一个 YAML 文件:

hello.yaml

foo:
    name: "hello\t"

在上述 YAML 文件中,正确引发了异常:

type of name: <class 'str'>, repr of name: 'hello\t'
Traceback (most recent call last):
  File "./test.py", line 16, in <module>
    raise Exception("No whitespace allowed in name!")
Exception: No whitespace allowed in name!

但是,如果我将双引号更改为单引号,则不会引发异常:

08:23 $ ./test.py 
type of name: <class 'str'>, repr of name: 'hello\\t'

在使用ruamel.yaml==0.11.11PyYAML=3.11 时都会出现这种情况。

为什么在这些 Python YAML 解析器中的单引号和双引号之间存在差异,而据我所知,在 YAML 规范中它们之间没有功能差异?如何防止特殊字符被转义?

【问题讨论】:

  • 什么yaml 模块是 Python3 原生的? ruamel.yamlPyYAML 都不是标准 python 库的一部分。
  • @Anthon 哎呀。我在全球范围内安装了 PyYAML,但没有意识到这一点。 :) 将编辑。

标签: python-3.x escaping yaml pyyaml ruamel.yaml


【解决方案1】:

单引号和双引号字符串之间的 YAML 规范存在巨大差异。在single quoted scalars 内只能转义单引号:

单引号样式由环绕的“'”指示符指定。因此,在单引号标量内,此类字符需要重复。这是在单引号标量中执行的唯一转义形式。

因此,'hello\t' 中的 \ 没有特殊功能,并且该标量由字母 hel (2x)、o 组成。 \t

反斜杠转义仅在双引号 YAML 标量中受支持。

【讨论】:

  • 啊,我的理解是错误的。 :) 我想我需要扩大我的限制以防止所有特殊字符。
  • 您可以在单引号中使用制表符(以及在文字和折叠块标量中),但您必须使用制表符本身,而不是通常的转义序列 (\t)。在许多情况下,这些字符很难与空格区分开来,但这是正确的 YAML
猜你喜欢
  • 2015-06-03
  • 1970-01-01
  • 2011-04-12
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
  • 2020-05-30
相关资源
最近更新 更多