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