【发布时间】:2019-08-07 11:58:17
【问题描述】:
使用 ruamel.yaml 转储 multiline 字符串会导致:
address_pattern_template: "\n^ #the beginning of the address\
\ string (e.g. interface number)\n(?P<junkbefore> #capturing the junk\
\ before the address\n \\D? #an optional non-digit character\n\
\ .*? #any characters (non-greedy) up to the address\n)\n\
(?P<address> #capturing the pure address\n {pure_address_pattern}\n\
)\n(?P<junkafter> #capturing the junk after the address\n \\D? \
\ #an optional non-digit character\n .* \
\ #any characters (greedy) up to the end of the string\n)\n$ \
\ #the end of the input address string\n"
代码是这样的:
from ruamel.yaml import YAML
data =dict(
address_pattern_template="""
^ #the beginning of the address string (e.g. interface number)
(?P<junkbefore> #capturing the junk before the address
\D? #an optional non-digit character
.*? #any characters (non-greedy) up to the address
)
(?P<address> #capturing the pure address
{pure_address_pattern}
)
(?P<junkafter> #capturing the junk after the address
\D? #an optional non-digit character
.* #any characters (greedy) up to the end of the string
)
$ #the end of the input address string
"""
)
yaml = YAML(typ='safe', pure=True)
yaml.default_flow_style = False
with open('D:\datadump.yml', 'w') as dumpfile:
yaml.dump(data, dumpfile)
我想查看可读格式的多行字符串。 IE。换行符用于换行而不是显示为 '\n'。
我可以设置哪些标志/选项使其如下所示:
address_pattern_template: |
^ #the beginning of the address string (e.g. interface number)
(?P<junkbefore> #capturing the junk before the address
\D? #an optional non-digit character
.*? #any characters (non-greedy) up to the address
)
(?P<address> #capturing the pure address
{pure_address_pattern}
)
(?P<junkafter> #capturing the junk after the address
\D? #an optional non-digit character
.* #any characters (greedy) up to the end of the string
)
$ #the end of the input address string
注意,我的程序记录了一个大字典,这样的多行字符串可以出现在字典结构的任何地方和任何深处。因此,遍历字典树并在转储之前加载它们中的每一个(如“我可以控制多行字符串的格式吗?”中所建议的那样)对我来说不是一个好的解决方案。
我想知道是否可以使用参数引导转储程序来识别多行字符串并以块格式转储它们。单行字符串仍然可以与冒号在同一行。这使得日志文件的可读性最高。
【问题讨论】:
-
不幸的是,该解决方案不适用于这个问题,所以我在请求中添加了一段解释它更好一点。
标签: string formatting dump ruamel.yaml