英文:
What should I do when I receive an error saying 'coroutine was never awaited' with asyncio.create_task?
问题
I want to create a task with asyncio.create_task, which must run in the background without blocking currently running function. However, when I attempt to create it, I get an error, saying that coroutine was never awaited.
我想使用asyncio.create_task创建一个任务,在后台运行,而不会阻塞当前运行的函数。然而,当我尝试创建它时,我收到一个错误,说协程从未被等待。
I tried to just call create_task() with a coroutine without awaiting it first, thinking that it would run after I created the task:
我尝试只是调用create_task(),使用一个协程而不等待它,认为它会在我创建任务后运行:
async def _turn_end_timer(self):
await asyncio.sleep(self.turn_time)
self.next_turn()
def next_turn(self):
if self._turn_worker is not None:
self._turn_worker.cancel()
if len(self.turn_queue) == 0:
self.current_turn_username = None
return
self.current_turn_username = self.turn_queue.pop(0)
coro = self._turn_end_timer()
self._turn_worker = asyncio.create_task(coro)
self.send_turn_queue_update()
That did not work. The event loop is running:
那不起作用。事件循环正在运行:
asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_forever()
What does that mean and how to fix it? I do not want to use threading
module, since it would cause more trouble.
这是什么意思以及如何修复它?我不想使用threading
模块,因为它会引起更多麻烦。
英文:
I want to create a task with asyncio.create_task, which must run in the background without blocking currently running function. However, when I attempt to create it, I get an error, saying that coroutine was never awaited.
I tried to just call create_task() with a coroutine without awaiting it first, thinking that it would run after I created the task:
async def _turn_end_timer(self):
await asyncio.sleep(self.turn_time)
self.next_turn()
def next_turn(self):
if self._turn_worker is not None:
self._turn_worker.cancel()
if len(self.turn_queue) == 0:
self.current_turn_username = None
return
self.current_turn_username = self.turn_queue.pop(0)
coro = self._turn_end_timer()
self._turn_worker = asyncio.create_task(coro)
self.send_turn_queue_update()
That did not work. The event loop is running:
asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_forever()
What does that mean and how to fix it? I do not want to use threading
module, since it would cause more trouble.
答案1
得分: 0
asyncio不允许多个事件循环同时运行,但如果您需要绕过这一限制,即您已经有一个正在运行的事件循环,那么您可以使用这个库
import nest_asyncio
nest_asyncio.apply()
这将允许多线程行为。
英文:
asyncio would not allow multiple event_loop to run but if you need a by pass that is you are getting the event_loop already running then you can use this library
import nest_asyncio
nest_asyncio.apply()
This will allow for a multi threaded behaviour
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论