2017-04-10 95 views
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 

如果我使用execexec(yaml_dict['treeroot']['branch1']['snap']),然後它打印出我想要的價值,但我不能捕獲值到一個變量。據我所知exec返回值是None。但是,我正在嘗試做一些與https://stackoverflow.com/a/23917810/1251660完全類似的操作,並且它不適用於我的情況。

回答

1

您可以使用exec這樣的:

import yaml 
import pprint 

with open('./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']())) 

,改變你的YAML這樣:

treeroot: 
    branch1: 
     name: Node 1 
     snap: | 
     def foo(): 
      return("test") 

    branch2: 
     name: Node 2 

其實,你可以使用exec(str, globals, locals

的內置函數globals()locals()返回當前全球和本地詞典,分別,其可以是圍繞通過用作第二和第三個參數exec()有用。

此外,你可以閱讀The exec Statement and A Python Mysterylocals and globals

+0

完美。這是我需要的。你能解釋一下這裏發生了什麼嗎?我無法正確解釋https://docs.python.org/3/library/functions.html#exec。 – slayedbylucifer

+1

@slayedbylucifer我試着解釋一下:) – RaminNietzsche