2017-04-10 96 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