May*_*tel 13 python yaml pretty-print pyyaml
我有一个python项目,我想使用YAML(pyYaml 3.11),特别是因为它"非常"且用户可以在必要时在文本编辑器中轻松编辑.但问题是,如果我将YAML带入python应用程序(我将需要)并编辑内容(因为我需要),那么编写新文档通常不如我开始时那么漂亮.
pyyaml文档非常差 - 甚至没有将参数记录到转储函数.我找到了http://dpinte.wordpress.com/2008/10/31/pyaml-dump-option/.但是,我仍然缺少我需要的信息.(我开始查看源代码,但它似乎并不是最吸引人的.如果我没有得到解决方案,那么这是我唯一的办法.)
我从一个看起来像这样的文档开始:
- color green :
inputs :
- port thing :
widget-hint : filename
widget-help : Select a filename
- port target_path :
widget-hint : path
value : 'thing'
outputs:
- port value:
widget-hint : string
text : |
I'm lost and I'm found
and I'm hungry like the wolf.
加载到python(yaml.safe_load(s))后,我尝试了几种方法将其转储出来:
>>> print yaml.dump( d3, default_flow_style=False, default_style='' )
- color green:
inputs:
- port thing:
widget-help: Select a filename
widget-hint: filename
- port target_path:
value: thing
widget-hint: path
outputs:
- port value:
widget-hint: string
text: 'I''m lost and I''m found
and I''m hungry like the wolf.
'
>>> print yaml.dump( d3, default_flow_style=False, default_style='|' )
- "color green":
"inputs":
- "port thing":
"widget-help": |-
Select a filename
"widget-hint": |-
filename
- "port target_path":
"value": |-
thing
"widget-hint": |-
path
"outputs":
- "port value":
"widget-hint": |-
string
"text": |
I'm lost and I'm found
and I'm hungry like the wolf.
理想情况下,我希望"短字符串"不使用引号,如第一个结果.但我希望将多行字符串写为块,与第二个结果一样.我想从根本上说,我试图最小化文件中不必要的引号的爆炸,我认为这会使在文本编辑器中编辑更加烦人.
有人对这个有经验么?
试试pyaml漂亮的打印机.它越来越接近了,尽管它确实在带有空格的短字符串周围加上引号:
>>> print pyaml.dump(d3)
- 'color green':
inputs:
- 'port thing':
widget-help: 'Select a filename'
widget-hint: filename
- 'port target_path':
value: thing
widget-hint: path
outputs:
- 'port value':
widget-hint: string
text: |
I'm lost and I'm found
and I'm hungry like the wolf.
Run Code Online (Sandbox Code Playgroud)
如果你可以使用ruamel.yaml(免责声明:我是这个增强版PyYAML的作者),你可以这样做:
import ruamel.yaml
yaml_str = """\
- color green :
inputs :
- port thing :
widget-hint : filename
widget-help : Select a filename
- port target_path :
widget-hint : path
value : 'thing'
outputs:
- port value:
widget-hint : string
text : |
I'm lost and I'm found
and I'm hungry like the wolf.
"""
data = ruamel.yaml.round_trip_load(yaml_str)
res = ""
for line in ruamel.yaml.round_trip_dump(data, indent=5, block_seq_indent=3).splitlines(True):
res += line[3:]
print(res)
Run Code Online (Sandbox Code Playgroud)
你得到:
- color green:
inputs:
- port thing:
widget-hint: filename
widget-help: Select a filename
- port target_path:
widget-hint: path
value: thing
outputs:
- port value:
widget-hint: string
text: |
I'm lost and I'm found
and I'm hungry like the wolf.
Run Code Online (Sandbox Code Playgroud)
不完全是你所做的事情(但在这次往返之后它是稳定的).使用更新版本的ruamel.yaml,您可以设置缩进内的序列的缩进和相对-缩进.然而,后者也会影响您的顶级序列,因此也会影响后期处理.
重要的(对我来说)保留的东西:注释,锚点,映射合并和文字标量(多行使用|)
| 归档时间: |
|
| 查看次数: |
20538 次 |
| 最近记录: |