【问题标题】:Asynchronous jobs in for loop in python [duplicate]python中for循环中的异步作业[重复]
【发布时间】:2020-12-20 11:19:26
【问题描述】:

我有一个函数

async def hello(a):
    await asyncio.sleep(2)
    print(a)

我想为列表中的几个元素异步调用这个函数

list =  ['words','I','need','to','print','parallely']

类似这样,但下面的代码一个接一个地运行。

for word in list:
    await hello(word)

有没有更好的方法来做到这一点?我用过asyncio.create_task,但不知道如何在循环中使用它们。

【问题讨论】:

  • 不要使用list作为变量名,它会影响内置类型list

标签: python asynchronous python-asyncio


【解决方案1】:

这是一个应该如何工作的示例:

import asyncio

list_1 = 'hi i am cool'.split()

async def hello(a):
    await asyncio.sleep(2)
    print(a)
    
async def run_tasks():
   tasks = [hello(word) for word in list_1]
   await asyncio.wait(tasks)

def main():
   loop = asyncio.new_event_loop()
   asyncio.set_event_loop(loop)
   loop.run_until_complete(run_tasks())
   loop.close()

main()

样本输出:

am
i
cool
hi

以上代码主要用于演示,但新的更简单的方法是:

def main2():
    asyncio.run(run_tasks())

main2()

样本输出:

i
hi
cool
am

注意:

按照 cmets 的建议,为了保持输入的顺序,将 run_tasks 定义为:

async def run_tasks():
   tasks = [hello(word) for word in list_1]
   await asyncio.gather(*tasks)

【讨论】:

  • 要保留输入的顺序,可以使用asyncio.gather(*tasks)
  • 你是这个意思吗?
  • 是的。如果你运行它,它应该按顺序打印“hi”“I”“am”“cool”。
  • RuntimeError: Cannot run the event loop while another loop is running 在运行 main() 时遇到上述相同代码的错误
  • import nest_asyncio nest_asyncio.apply() 添加了这两行并且它的工作!谢谢
猜你喜欢
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 2017-02-25
  • 2020-10-18
  • 1970-01-01
  • 2018-07-15
相关资源
最近更新 更多