繁体   English   中英

如何使用 ruamel.yaml 包编辑 yaml 文件,而不更改文件的缩进?

[英]How do I edit a yaml file using ruamel.yaml package, without changing the indentation of the file?

我正在使用Anthon 在这里提出的代码,但它似乎不起作用。

YAML 文件:

init_config: {}
instances:
    - host: <IP>              # update with IP
      username: <username>    # update with user name
      password: <password>    # update with password

代码:

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)

预期输出:

init_config: {}
instances:
    - host: 1.2.3.4           # update with IP
      username: Username      # update with user name
      password: Password      # update with password

我得到的输出:

init_config: {}
instances:
- host: 1.2.3.4           # update with IP
  username: Username      # update with user name
  password: Password      # update with password

我做错了什么,还是这个例子坏了? 我怎样才能得到预期的输出?

在更新该答案版本 4 中旧的round_trip_dump例程以使用YAML()某个地方,我忘记将参数indentblock_seq_indent更改为对.indent()方法的调用,如该答案的最后一个代码部分所示.

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)

这使:

init_config: {}
instances:
    - host: 1.2.3.4           # update with IP
      username: Username      # update with user name
      password: Password      # update with password

当我回答 SO 时,我通常会制作一个 .ryd 文件。 该文件具有文本和代码段,并且在处理时以答案的形式与代码输出的结果相结合,我可以将其粘贴到 SO 上。 这样,代码和输出之间永远不会有差异。

但是这个答案是在我开始使用它之前的,我在更新它时没有为旧答案制作 .ryd 文件。 我应该...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM