xyz
xyz

Reputation: 306

execute python script written in yaml with variables

I'm trying to execute python line written in YAML file with YAML scalar value as a variable.

My code:

with open("file.yaml", "r") as file:
    yaml_ = yaml.load(file)

eval(yaml_['Code'])

file.yaml:

ToPrint:
  var: something
Code: print("{{var}}")

Output is: {{var}} (my expected output: something ).

Is there a way to print YAML field that way?

Upvotes: 1

Views: 3159

Answers (3)

Viach
Viach

Reputation: 508

extended Daniel's answer:

yaml-file:

Const:
    c1: 10
    c2: 20
Expression: var1 * var2 + c1 / c2

code:

import yaml

with open("formula.yaml", "r") as file:
    yaml_ = yaml.load(file)

res = eval(yaml_['Expression'], 
           {'var1':4, 'var2':2}, 
           yaml_['Const'])
print(res)

Upvotes: 0

Anthon
Anthon

Reputation: 76842

I would change the YAML file to read:

ToPrint:
  var: something
Code: print("{var}".format(**d['ToPrint']))

And since you are using Python3 also use Path:

import sys
import ruamel.yaml
from pathlib import Path

yaml = ruamel.yaml.YAML()
d = yaml.load(Path('file.yaml'))
eval(d['Code'])

which gives:

something

Please note that the variable d has to be the same as the one in the value for Code

The use of {{var}} looks more like a (jinja2) template. You cannot directly eval those, you would need to expand the template and then all eval.

Upvotes: 2

Daniel
Daniel

Reputation: 42778

You can use ToPrint as local variables in eval:

with open("file.yaml", "r") as file:
    yaml_ = yaml.load(file)

eval(yaml_['Code'], yaml_['ToPrint'])

And the yaml-file:

ToPrint:
  var: something
Code: print(f"{var}")

Upvotes: 1

Related Questions