python - Is it possible to preserve YAML block structure when dumping a parsed document? -


we use pyyaml prep config files different environments. our yaml blocks lose integrity.

give input.yml ...

pubkey: |     -----begin public key-----     migfma0gcsq7opxrrqebaquaa4gnadcbiqkbgqcvrvukp6pr4qbene9lviuyfinq     qtg/ocybdxl4bh3fmuzfni+z4bh3fmux+z2n0fcv/4bpghtdl8d95npopwvo1rh2     ufhymd6dq/x9t5m+y38jmzmsvak+fqu8ya18+yqvoeyeix3gxpsgegow33gcxfjk     esugjhxcpw7opxrrcqidaqab     -----end public key----- 

... executing program using python3 ...

import yaml  open('input.yml', mode='r') f:     parsed = yaml.safe_load(f)  open('output.yml', mode='w') f:     yaml.dump(parsed, f) 

... produces output.yml ...

pubkey: '-----begin public key-----      migfma0gcsq7opxrrqebaquaa4gnadcbiqkbgqcvrvukp6pr4qbene9lviuyfinq      qtg/ocybdxl4bh3fmuzfni+z4bh3fmux+z2n0fcv/4bpghtdl8d95npopwvo1rh2      ufhymd6dq/x9t5m+y38jmzmsvak+fqu8ya18+yqvoeyeix3gxpsgegow33gcxfjk      esugjhxcpw7opxrrcqidaqab      -----end public key-----      ' 

is possible preserve structure of block using pyyaml?

yes possible pyyaml, have provide own enhanced versions of @ least scanner, parser , constructor used safe_load, emitter, serializer , representer used dump, , providing specialized string-like class keeps information it's original formatting.

this part of added ruamel.yaml (disclaimer: author of package) derived pyyaml , still keeps similar setup. using ruamel.yaml:

import ruamel.yaml yaml  yaml_str = """\ pubkey: |     -----begin public key-----     migfma0gcsq7opxrrqebaquaa4gnadcbiqkbgqcvrvukp6pr4qbene9lviuyfinq     qtg/ocybdxl4bh3fmuzfni+z4bh3fmux+z2n0fcv/4bpghtdl8d95npopwvo1rh2     ufhymd6dq/x9t5m+y38jmzmsvak+fqu8ya18+yqvoeyeix3gxpsgegow33gcxfjk     esugjhxcpw7opxrrcqidaqab     -----end public key----- """  data = yaml.load(yaml_str, loader=yaml.roundtriploader) print(yaml.dump(data, dumper=yaml.roundtripdumper, indent=4)) 

gives you:

pubkey: |     -----begin public key-----     migfma0gcsq7opxrrqebaquaa4gnadcbiqkbgqcvrvukp6pr4qbene9lviuyfinq     qtg/ocybdxl4bh3fmuzfni+z4bh3fmux+z2n0fcv/4bpghtdl8d95npopwvo1rh2     ufhymd6dq/x9t5m+y38jmzmsvak+fqu8ya18+yqvoeyeix3gxpsgegow33gcxfjk     esugjhxcpw7opxrrcqidaqab     -----end public key----- 

at least python 2.7 , 3.5.

the indent=4 necessary roundtripdumper defaults 2 spaces indent , original indent of file not preserved (not doing eases re-indenting yaml file).

if cannot switch ruamel.yaml should able use source extract changes needed, if can can use other features comment , merge key name preservation.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -