Search code examples
pythonyamlpyyaml

Execute Python code embedded in YAML file


I'm wondering if it's possible to execute Python code that's embedded in a YAML file. For example, my YAML file currently contains a list:

list: [1,2,3,4]

But I'd prefer to enter this list in my YAML file using numpy:

list: np.arange(1,5)

I saw "How to embed Python code into YAML?" describing how to embed the Python code using literal scalar block style, but it doesn't describe how to actually execute the embedded code.


Solution

  • It is possible. The following Python script will do just that provided that your YAML file is named data.yml.

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

    Also make sure to add the imports in your Python code in the YAML file:

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