0
yaml
文件:捕获返回值从高管
$ cat ec2_attr.yml
treeroot:
branch1:
name: Node 1
snap: |
def foo():
from boto3.session import Session
import pprint
session = Session(region_name='us-east-1')
client = session.client('rds')
resp = client.describe_db_cluster_snapshots(
SnapshotType='manual',
)
filtered = [x for x in resp['DBClusterSnapshots'] if x[
'DBClusterSnapshotIdentifier'].startswith('xxxxx')]
latest = max(filtered, key=lambda x: x['SnapshotCreateTime'])
print(latest['DBClusterSnapshotIdentifier'])
foo()
branch2:
name: Node 2
代码:
import yaml
import pprint
with open('./ec2_attr.yml') as fh:
try:
yaml_dict = yaml.load(fh)
except Exception as e:
print(e)
else:
exec("a = yaml_dict['treeroot']['branch1']['snap']")
print('The Value is: %s' % (a))
实际输出:
The Value is: def foo():
from boto3.session import Session
import pprint
session = Session(region_name='us-east-1')
client = session.client('rds')
resp = client.describe_db_cluster_snapshots(
SnapshotType='manual',
)
filtered = [x for x in resp['DBClusterSnapshots'] if x[
'DBClusterSnapshotIdentifier'].startswith('xxxxx')]
latest = max(filtered, key=lambda x: x['SnapshotCreateTime'])
print(latest['DBClusterSnapshotIdentifier'])
foo()
预期输出:
xxxxx-xxxx-14501111111-xxxxxcluster-2gwe6jrnev8a-2017-04-09
如果我使用exec
为exec(yaml_dict['treeroot']['branch1']['snap'])
,然后它打印出我想要的价值,但我不能捕获值到一个变量。据我所知exec
返回值是None
。但是,我正在尝试做一些与https://stackoverflow.com/a/23917810/1251660完全类似的操作,并且它不适用于我的情况。
完美。这是我需要的。你能解释一下这里发生了什么吗?我无法正确解释https://docs.python.org/3/library/functions.html#exec。 – slayedbylucifer
@slayedbylucifer我试着解释一下:) – RaminNietzsche