无法将变量值从一个函数传递到另一个函数

时间:2018-03-26 07:33:33

标签: python boto3

我是Python新手并尝试过类似的建议而失败了。

我正在编写一个由少数函数组成的脚本,第一个函数将创建一些将在其他函数中使用的变量(它不能是全局变量)。 当我尝试了我的脚本时,我不断为未定义的变量获取NameError。

import boto3
import json
from awsretry import AWSRetry
from botocore.exceptions import ClientError

@AWSRetry.backoff(tries=5)

def instance_details(event, context):    
    client = boto3.client('ec2')]
    ec2_resource = boto3.resource('ec2')`
    alert = event['Records'][0]['Sns']['Message']
    instance_id = alert['Trigger']['Dimensions'][0]['value']
    instance = ec2_resource.Instance(instance_id)
    return client 

@AWSRetry.backoff(tries=5)

def tagging():
    instance_type = instance['Reservations'][0]['Instances'][0]['InstanceType']

为什么我无法将instanceclient的值传递给其他函数?

提前致谢并抱歉重复。

1 个答案:

答案 0 :(得分:2)

intance_details我相信是lambda处理程序方法。由于您正在撤回客户端,我相信您应该能够在变量中看到客户端值,您将在该变量中捕获此方法的返回值。

除此之外,您可以尝试在此处使用Class并在__init__方法中声明这些变量。然后在lambda处理程序中创建该类的实例并访问这些变量。然后你就可以在整个班级中使用这些变量了。

import boto3
class Answer:
    def __init__(self):
        self.instance = None
        self.client = boto3.client('ec2')]
        self.ec2_resource = boto3.resource('ec2')

    def meth1(self):
        # suppose here we want to use the value of instance
        # using self.instance you can use the value of instance here
        # you can pass the alert from lambda_handler to this method 
        # as well and do all the computation here too.
        print(self.client) # example how to use class variables.

def lambda_handler(event, context):
    ans = Answer()
    alert = event['Records'][0]['Sns']['Message']
    instance_id = alert['Trigger']['Dimensions'][0]['value']
    ans.instance = ans.ec2_resource.Instance(instance_id)
    # if you want to pass instance id, you can pass in the arguments and
    # change the definition of meth1 accordingly.
    # Apart form that you can pass the alert in the meth1 too and do all the computation there.
    ans.meth1()

if __name__ == "__main__":
    lambda_handler(event, "")
相关问题