Ce snippet asyncio montre comment obtenir la boucle d’événements en cours d’exécution ou créer une nouvelle boucle si aucune n’est en cours d’exécution.
get_or_create_eventloop.py
import asyncio
def get_or_create_eventloop():
try:
return asyncio.get_event_loop()
except RuntimeError as ex:
if "There is no current event loop in thread" in str(ex):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return asyncio.get_event_loop()
else:
raise
# Usage example:
get_or_create_eventloop().create_task(asyncio.sleep(1))
Consultez les articles similaires par catégorie :
Python
Si cet article vous a aidé, pensez à m'offrir un café ou à faire un don via PayPal pour soutenir la recherche et la publication de nouveaux articles sur TechOverflow