我有一個YAML文件,並希望限制某個字段不包含空格。爲什麼PyYAML和ruamel.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.11
和PyYAML=3.11
時都會發生。
爲什麼這些Python YAML解析器中的單引號和雙引號之間有區別,據我所知,它們在YAML規範中沒有功能差異?我如何防止特殊字符被轉義?
什麼'yaml'模塊是Python3原生的? 'ruamel.yaml'和'PyYAML'都不是標準python庫的一部分。 – Anthon
@Anthon哎呀。我在全球安裝了PyYAML,但沒有意識到它。 :)將編輯。 – erip