from ruamel.yaml import YAML
yaml=YAML(typ='safe')
yaml.load(doc)
以上typ若没有指定,默认为 'rt' (round-trip);
doc可以是文件指针(即具有.read()方法、字符串或pathlib.Path()的对象);
typ='safe'完成了与safe_load()之前相同的操作:加载文档而不解析未知标记;
pure=True以使用纯Python实现强制执行,否则将在可能/可用时使用更快的C库。
详细的可以参考源码:
代码语言:python代码运行次数:0复制
class YAML:
def __init__(self, *, typ=None, pure=False, output=None, plug_ins=None): # input=None,
# type: (Any, Optional[Text], Any, Any, Any) -> None
"""
typ: 'rt'/None -> RoundTripLoader/RoundTripDumper, (default)
'safe' -> SafeLoader/SafeDumper,
'unsafe' -> normal/unsafe Loader/Dumper
'base' -> baseloader
pure: if True only use Python modules
input/output: needed to work as context manager
plug_ins: a list of plug-in files
"""
代码语言:python代码运行次数:0复制
def load(self, stream):
# type: (Union[Path, StreamTextType]) -> Any
"""
at this point you either have the non-pure Parser (which has its own reader and
scanner) or you have the pure Parser.
If the pure Parser is set, then set the Reader and Scanner, if not already set.
If either the Scanner or Reader are set, you cannot use the non-pure Parser,
so reset it to the pure parser and set the Reader resp. Scanner if necessary
"""
if not hasattr(stream, 'read') and hasattr(stream, 'open'):
# pathlib.Path() instance
with stream.open('rb') as fp:
return self.load(fp)
constructor, parser = self.get_constructor_parser(stream)
try:
return constructor.get_single_data()
finally:
parser.dispose()
try:
self._reader.reset_reader()
except AttributeError:
pass
try:
self._scanner.reset_scanner()
except AttributeError:
pass
def tr(s):
return s.replace('n', '<n') # such output is not valid YAML!
yaml.dump(data, sys.stdout, transform=tr)
详细查看源码:
代码语言:python代码运行次数:0复制
def dump(self, data, stream=None, *, transform=None):
# type: (Any, Union[Path, StreamType], Any, Any) -> Any
if self._context_manager:
if not self._output:
raise TypeError('Missing output stream while dumping from context manager')
if transform is not None:
raise TypeError(
'{}.dump() in the context manager cannot have transform keyword '
''.format(self.__class__.__name__)
)
self._context_manager.dump(data)
else: # old style
if stream is None:
raise TypeError('Need a stream argument when not dumping from context manager')
return self.dump_all([data], stream, transform=transform)
3.3 基于C的SafeLoader
代码语言:python代码运行次数:0复制
from ruamel.yaml import YAML
yaml=YAML(typ="safe")
yaml.load("""a:n b: 2n c: 3n""")