Wie man asyncio RuntimeError behebt: This event loop is already running

Problem

Beim Versuch, eine async def-Funktion mit asyncio.run_until_complete() auszuführen, z.B.

asyncio_example.py
import asyncio
asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))

siehst du eine Fehlermeldung wie

asyncio_runtimeerror_example.txt
Cell In[3], line 15
     12           raise
     14 # Usage example:
---> 15 asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))

File /usr/lib/python3.12/asyncio/base_events.py:663, in BaseEventLoop.run_until_complete(self, future)
    652 """Run until the Future is done.
    653
    654 If the argument is a coroutine, it is wrapped in a Task.
   (...)
    660 Return the Future's result, or raise its exception.
    661 """
    662 self._check_closed()
--> 663 self._check_running()
    665 new_task = not futures.isfuture(future)
    666 future = tasks.ensure_future(future, loop=self)

File /usr/lib/python3.12/asyncio/base_events.py:622, in BaseEventLoop._check_running(self)
    620 def _check_running(self):
    621     if self.is_running():
--> 622         raise RuntimeError('This event loop is already running')
    623     if events._get_running_loop() is not None:
    624         raise RuntimeError(
    625             'Cannot run the event loop while another loop is running')

RuntimeError: This event loop is already running

Lösung

Verwende statt loop.run_until_complete() asyncio.create_task(), um die Koroutine auszuführen:

asyncio_create_task.py
future = asyncio.get_event_loop().create_task(asyncio.sleep(1))

Optional kannst du den Future awaiten, um auf den Abschluss der Koroutine zu warten:

asyncio_await_future.py
await future

Der Grund dafür ist, dass loop.run_until_complete() für synchronen Code gedacht ist und die Schleife immer starten wird, daher wird es fehlschlagen, wenn die Schleife bereits läuft.

Typischerweise tritt dieser Fehler auf, wenn du Code aus einem Kontext wie einem Jupyter-Notebook ausführst, das intern eine Event-Loop startet. Möglicherweise musst du deinen Code ändern, wenn du ihn in einem anderen Kontext wie einem reinen Python-Skript ausführen möchtest.


Ähnliche Beiträge nach Kategorie: Python