繁体   English   中英

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

[英]Can't pass variable value from one function to another

我是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的值传递给其他函数?

在此先感谢您,并感谢您重复。

我认为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, "")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM