如何将 Python 代码嵌入到 YAML 中? [英] How to embed Python code into YAML?

查看:40
本文介绍了如何将 Python 代码嵌入到 YAML 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 Python 代码嵌入到 YAML 文档中.该文档最好是可移植的(标准 YAML),或者至少可以被 Python 解析(例如使用 PyYaml).

事实上,我试图将未修改的字符串包含到 yaml 属性中.应保留缩进和换行符,以便稍后执行嵌入的 Python 代码.

我找到了>",但它删除了换行符.

解决方案

您可以使用 文字标量块样式,由 | 引入.例如:

<前>代码: |定义 foo():打印foo"# 我们可以毫无困难地包含空行富()

如果您需要从代码生成文件,那么 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆