如何将 Python 代码嵌入到 YAML 中? [英] How to embed Python code into YAML?
问题描述
我需要将 Python 代码嵌入到 YAML 文档中.该文档最好是可移植的(标准 YAML),或者至少可以被 Python 解析(例如使用 PyYaml).
事实上,我试图将未修改的字符串包含到 yaml 属性中.应保留缩进和换行符,以便稍后执行嵌入的 Python 代码.
我找到了>",但它删除了换行符.
您可以使用 文字标量块样式,由 |
引入.例如:
如果您需要从代码生成文件,那么 yaml
模块确实具有允许您控制块样式的功能:Python 中任何支持将长字符串转储为块文字或折叠块的 yaml 库?
感谢@delnan 为我指出这些非常有用的信息.
I need to embed Python code into a YAML document. The document should preferably be portable (standard YAML), or at least parsable by Python (using PyYaml for example).
In fact I'm trying to include unmodified strings into yaml attributes. Indentations and new lines should be kept, so that embedded Python code could then be executed later.
I found the '>' but it removes newlines.
You can use the literal scalar block style, introduced with |
. For instance:
code: | def foo(): print "foo" # we can include blank lines with no difficulty foo()
If you need to generate the file from code, then the yaml
module does have functionality that allows you to control the block style: Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?
Thanks to @delnan for pointing me towards this very useful information.
这篇关于如何将 Python 代码嵌入到 YAML 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!