我有一个 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 文件的第一个剪切:
你好.yaml
foo:
name: "hellot"
在上面的 YAML 文件中,正确引发了异常:
type of name: <class 'str'>, repr of name: 'hellot'
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.11
和 PyYAML=3.11
时都会发生此行为。
和双引号之间存在差异,而据我了解,它们在 YAML 规范中没有功能差异?如何防止特殊字符被转义?
单引号和双引号字符串之间的 YAML 规范存在巨大差异。在单引号标量中,您只能转义单引号:
单引号样式由周围的 "'" 指示符指定。因此,在单引号标量中,需要重复此类字符。这是在单引号标量中执行的唯一转义形式。
因此在
'hellot'
中没有特殊功能,标量由字母h
、e
、l
(2x)、o
组成。 和
t
反斜杠转义仅在双引号的 YAML 标量中受支持。