简体   繁体   English

Python:使用从一个函数返回的值到另一个函数

[英]Python: Use returned values from a function to another function

With the simple function I am able to get data stored in response variable. 通过简单的功能,我可以获取存储在响应变量中的数据。 With a print statement I can get the data showing correctly. 使用打印语句,我可以正确显示数据。

ec2_client = boto3.client("ec2")
def instance_list(instance_name):
    response = ec2_client.describe_instances(
        Filters=[
            {
                'Name': 'tag:Name',
                'Values': [ instance_name ]
            }
        ]
    )['Reservations']
    return response
    #print(response)

if __name__ == '__main__':
    my_instance_list = instance_list("example-*")

However while trying to import the value of response from the above function to another function, getting error as NameError: name 'response' is not defined 但是,当尝试将上述函数的响应值导入到另一个函数时,由于NameError: name 'response' is not defined出现错误NameError: name 'response' is not defined

def my_list():
    list = instance_list(response)
    print(list)

Looks like something unidentified. 看起来像是未知的东西。

您需要将变量传递给下一个函数,例如

my_list(instance_list())

the basic idea is to use return value of one function to another function 基本思想是使用一个函数的返回值到另一个函数

Your function should be this: 您的功能应为:

def my_list():
    # List is equal to the response value of instance list.
    list = instance_list("example-*")

    print(list)

Easy example 简单的例子

def add_five_to_number(number):
   number += 5
   return number

def print_number(number):
   higher_number = add_five_to_number(number)   
   print(higher_number)

test_number = 3
print_number(test_number)

# Returns 8

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

相关问题 如何在另一个函数中使用一个函数的两个返回值? 主要() - How to use two returned values from a function in another function? MAIN() 无法将返回的值从函数传递给python中的另一个函数 - Cannot pass returned values from function to another function in python 如何在另一个 function 中使用前一个 function 返回的变量? (Python) - How to use a returned variable from a previous function in another function? (python) 通过另一个函数访问一个函数的返回值 - Accessing returned values from a function, by another function 如何使用itertools将返回的值从一个函数传递给另一个函数? - How to use itertools to pass the returned values from one function to another? Python3:在另一个文件中打印函数返回的值 - Python3 : Print returned values from the function in another file python 将另一个 function 的返回值设置为在 header 中使用的变量 - python set returned value from another function as a variable to use in header 使用来自另一个 function python3 的值 - Use values from another function python3 使用函数的返回值作为另一个 function 的参数 - Use a function's returned values as parameters for another function Python:在另一个函数中调用具有返回值的函数:错误处理? - Python: Calling a function inside another function with returned values: Error Handling?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM