Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从exec捕获返回值_Python - Fatal编程技术网

Python 从exec捕获返回值

Python 从exec捕获返回值,python,Python,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')

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
代码:

$ 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
实际输出:

$ 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
预期输出:

$ 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
。但是,我正在尝试执行与完全类似的操作,但在我的情况下不起作用。

您可以像这样使用
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()


此外,您还可以阅读和使用
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()


此外,您还可以阅读和完善。这就是我需要的。你能解释一下这是怎么回事吗。我不能正确地解释。@slayedbylucifer我试图再解释一点:)完美。这就是我需要的。你能解释一下这是怎么回事吗。我无法正确解释。@slayedbylucifer我试图再解释一点:)