如何从收集方法中获取 return 值

how get I a return value from a gather method

我想获得 task_2 函数的 return 值,但它无法按我希望的方式工作。 实际上,我希望 task_2 函数中的 return 作为主函数中的可用值,以便我可以将它用于另一个函数

class test_class():
    def __init__(self):
        self.list_el = [1,2,3,4,5,6]
        self.loop = asyncio.get_event_loop()


    def main(self):
        return_value = self.loop_1()
        print(return_value)

    def loop_1(self):
        output = self.loop.run_until_complete(self.task_1())
        return output

    async def task_1(self):
        tasks = []
        for i in self.list_el:
            tasks.append(asyncio.create_task(self.task_2(i)))
        return tasks

    async def task_2(self,number):
        odd = []
        even = []
        if number % 2 ==0:
            print("even")
            even.append(number)
        else:
            print("odd")
            odd.append(number)

        return even,odd

if __name__ == "__main__":
    app =test_class()
    app.main()

来自 self.loop_1() 的 return 值已经包含您需要的一切。如果您查看程序的输出,您会看到 print(return_value) 打印出如下内容:

[<Task finished name='Task-2' coro=<test_class.task_2() done, defined at /home/lars/tmp/python/astest.py:27> result=([], [1])>, <Task finished name='Task-3' coro=<test_class.task_2() done, defined at /home/lars/tmp/python/astest.py:27> result=([2], [])>,...]

查看其中一个值,我们看到:

<Task finished name='Task-2' coro=<test_class.task_2() done,
defined at /home/lars/tmp/python/astest.py:27> 
result=([], [1])>

你可以在result属性中看到你想要的值。因此,您只需要遍历 returned Task 个对象并从每个对象中获取结果:

import asyncio


class test_class:
    def __init__(self):
        self.list_el = [1, 2, 3, 4, 5, 6]

    def main(self):
        return_value = self.loop_1()
        for task in return_value:
            odd, even = task.result()
            print(f"odd {odd} even {even}")

    def loop_1(self):
        loop = asyncio.get_event_loop()
        output = loop.run_until_complete(self.task_1())
        return output

    async def task_1(self):
        tasks = []
        for i in self.list_el:
            tasks.append(asyncio.create_task(self.task_2(i)))
        return tasks

    async def task_2(self, number):
        odd = []
        even = []
        if number % 2 == 0:
            print("even")
            even.append(number)
        else:
            print("odd")
            odd.append(number)

        return even, odd


if __name__ == "__main__":
    app = test_class()
    app.main()