【问题标题】:Execute Python code embedded in YAML file执行嵌入在 YAML 文件中的 Python 代码
【发布时间】:2014-11-21 14:58:33
【问题描述】:

我想知道是否可以执行嵌入在 YAML 文件中的 Python 代码。例如,我的 YAML 文件当前包含一个列表:

list: [1,2,3,4]

但我更喜欢使用 numpy 在我的 YAML 文件中输入此列表:

list: np.arange(1,5)

我看到“How to embed Python code into YAML?”描述了如何使用文字标量块样式嵌入 Python 代码,但它没有描述如何实际执行嵌入的代码。

【问题讨论】:

标签: python yaml pyyaml


【解决方案1】:

这是可能的。如果您的 YAML 文件名为 data.yml,则以下 Python 脚本将执行此操作。

import yaml
with open("data.yml", "r") as f:
    data = yaml.load(f)
exec data['list']

还要确保在 YAML 文件中的 Python 代码中添加导入:

list: |
    import numpy as np
    print np.arange(1,5)

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多