Capture Return Value From Exec
yaml file: $ cat ec2_attr.yml treeroot: branch1: name: Node 1 snap: | def foo(): from boto3.session import Session impor
Solution 1:
You can use exec
like this:
import yaml
import pprint
withopen('./a.yaml') as fh:
try:
yaml_dict = yaml.load(fh)
except Exception as e:
print(e)
else:
a = {}
exec(yaml_dict['treeroot']['branch1']['snap'], {}, a)
print('The Value is: %s' % (a['foo']()))
And change your YAML to this:
treeroot:branch1:name:Node1snap:|
def foo():
return("test")
branch2:name:Node2
Actually, You can use exec(str, globals, locals
)
The built-in functions globals()
and locals()
return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec()
.
Also, You can read The exec Statement and A Python Mystery and locals and globals
Post a Comment for "Capture Return Value From Exec"