I am using the code proposed here by Anthon but it doesn't seem to work.
YAML file:
init_config: {}
instances:
- host: <IP> # update with IP
username: <username> # update with user name
password: <password> # update with password
Code:
import ruamel.yaml
yaml = ruamel.yaml.YAML()
file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))
instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'
with open('output.yaml', 'w') as fp:
yaml.dump(config, fp)
Expected output:
init_config: {}
instances:
- host: 1.2.3.4 # update with IP
username: Username # update with user name
password: Password # update with password
Output that I get:
init_config: {}
instances:
- host: 1.2.3.4 # update with IP
username: Username # update with user name
password: Password # update with password
Am I doing something wrong, or is the example broken? How can I get the expected output?
Somewhere in updating the old round_trip_dump
routine in version 4 of that answer to use the YAML()
, I forgot to change the arguments indent
and block_seq_indent
to a call to the .indent()
method, as shown in the last code section of that answer.
import sys
import ruamel.yaml
import ruamel.yaml
from ruamel.yaml import YAML
yaml=YAML()
file_name = 'input.yaml'
config, ind, bsi = ruamel.yaml.util.load_yaml_guess_indent(open(file_name))
instances = config['instances']
instances[0]['host'] = '1.2.3.4'
instances[0]['username'] = 'Username'
instances[0]['password'] = 'Password'
yaml.indent(mapping=ind, sequence=ind, offset=bsi) # <<<< missing
yaml.dump(config, sys.stdout)
which gives:
init_config: {}
instances:
- host: 1.2.3.4 # update with IP
username: Username # update with user name
password: Password # update with password
I normally make a single .ryd file when I answer on SO. That file has both text and code segments and when processed gets combined with the results of the code output in the form of an answer that I can paste in on SO. That way there is never a discrepancy between code and output.
But that answer is from before I started using that, and I didn't make the .ryd file for the old answer when I updated it. I should have...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.