Ticket #183: yaml_test.py

File yaml_test.py, 1.6 KB (added by matkor, 3 years ago)
Line 
1# -*- coding: utf-8 -*-
2
3import yaml
4from yaml import events
5
6binarydata = [chr(i) for i in xrange(256) ]
7binarydata = "".join(binarydata)
8print "binarydata: %r" % (binarydata, )
9
10def dump_dict(dumper,  d):
11    dumper.emit( events.MappingStartEvent(anchor=None, tag=None, implicit=True) )
12   
13    for k, v in d.items():
14        dumper.emit( events.ScalarEvent(anchor=None, tag=None, implicit=(True, False), value=k) )
15        dumper.emit( events.ScalarEvent(anchor=None, tag=None, implicit=(True, False), value=v) )
16
17    dumper.emit( events.MappingEndEvent() )
18   
19   
20dump_fn = "test.yaml"
21print ("Saving to file: %r " % (dump_fn, ))
22dumpf = open(dump_fn, "wb")
23# http://pyyaml.org/wiki/PyYAMLDocumentation
24dumper = yaml.CSafeDumper(dumpf)
25
26# dumper.emit( yaml.StreamStartEvent(encoding='utf-8') )
27# dumper.emit( yaml.DocumentStartEvent() )
28dumper.open()
29
30# dumper.emit( yaml.events.StreamStartEvent() )
31dumper.emit( events.DocumentStartEvent() )
32
33# MappingStartEvent(anchor=None, tag=None, implicit=True)
34dumper.emit( events.MappingStartEvent(anchor=None, tag=None, implicit=True) )
35
36dumper.emit( events.ScalarEvent(anchor=None, tag=None, implicit=(True, False), value='1') )
37dumper.emit( events.ScalarEvent(anchor=None, tag=None, implicit=(True, False), value='one') )
38
39dumper.emit( events.ScalarEvent(anchor=None, tag=None, implicit=(True, False), value='2') )
40dump_dict(dumper,  {"intro":"intro_value",  "desc": "long description",  "multiline": "line 1\nline2\nline3\n",  "binary": binarydata })
41
42dumper.emit( events.MappingEndEvent() )
43
44
45dumper.emit( events.DocumentEndEvent(explicit=True) )
46# dumper.emit( yaml.StreamEndEvent() )
47dumper.close()