对运行异步函数的函数的多次调用:将事件循环放置在何处?

2024-10-01 10:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试多次调用函数。此函数在其中运行异步函数。代码如下所示:

 import asyncio

 async def add(x):
     return x + 1


 def my_func(nums):
     loop = asyncio.get_event_loop()   # where should I put this statement?
     res = loop.run_until_complete(
         asyncio.gather(*[add(x) for x in nums]))

     return res


 def main():
     batch1 = [1, 2, 3]
     batch2 = [4, 5, 6]

     print(my_func(batch1))
     print(my_func(batch2))


 if __name__ == "__main__":
     main()

我的问题是我应该把声明放在哪里。我应该把它放在my_func内,还是只把它放在全局级别并使其成为全局变量,例如,把它放在import asyncio下面

最佳做法是什么


Tags: 函数importloopaddasyncioreturnmainmy