Capture Return Value from exec

后端 未结 1 1432
无人及你
无人及你 2021-01-28 02:57

yaml file:

$ cat ec2_attr.yml

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

              from         


        
相关标签:
1条回答
  • 2021-01-28 03:13

    You can use exec like this:

    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']()))
    

    And change your YAML to this:

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

    Actually, You can use exec(str, globals, locals)

    • globals()
    • locals()

    The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec().

    Also, You can read The exec Statement and A Python Mystery and locals and globals

    0 讨论(0)
提交回复
热议问题