From 874f0f01f6159c953c12c1cc251484b9b3381ae4 Mon Sep 17 00:00:00 2001 From: Bastian Krause Date: Thu, 1 Aug 2024 15:18:16 +0200 Subject: [PATCH] remote: use more explicit event loop handling Calling asyncio.get_event_loop() with no current event loop is deprecated since Python 3.10 and will be an error in some future Python release [1]. Whenever we don't expect to run with an event loop, create one explicitly. In coroutine and callbacks from asynchronous code, use the more explicit asyncio.get_running_loop() to get the loop. Note that this does not work in labgrid.resources.ethernetport.EthernetPortManager: This code is usually not called in coroutines and callbacks from asynchronous code, so asyncio.get_running_loop() does not work there. So stick to asyncio.get_event_loop() there and just expect to be called with a running event loop (which is the non-deprecated use case for this function). Users that do not have an event loop running will see a justified DeprecationWarning with Python >= 3.12 and an error in some future Python version. [1] https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop Signed-off-by: Bastian Krause --- labgrid/remote/coordinator.py | 6 ++++-- labgrid/remote/exporter.py | 5 ++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/labgrid/remote/coordinator.py b/labgrid/remote/coordinator.py index 635c7c5c9..97ed16d26 100644 --- a/labgrid/remote/coordinator.py +++ b/labgrid/remote/coordinator.py @@ -194,7 +194,7 @@ def __init__(self) -> None: self.clients: dict[str, ClientSession] = {} self.load() - self.loop = asyncio.get_event_loop() + self.loop = asyncio.get_running_loop() self.poll_task = self.loop.create_task(self.poll()) async def _poll_step(self): @@ -1025,7 +1025,9 @@ def main(): logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO) - loop = asyncio.get_event_loop() + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + cleanup = [] loop.set_debug(True) try: diff --git a/labgrid/remote/exporter.py b/labgrid/remote/exporter.py index 64ddb4032..95d331e90 100755 --- a/labgrid/remote/exporter.py +++ b/labgrid/remote/exporter.py @@ -778,7 +778,7 @@ def __init__(self, config) -> None: - Setup loop, name, authid and address - Join the coordinator as an exporter""" self.config = config - self.loop = asyncio.get_event_loop() + self.loop = asyncio.get_running_loop() self.name = config["name"] self.hostname = config["hostname"] self.isolated = config["isolated"] @@ -1061,6 +1061,9 @@ def main(): print(f"exporter hostname: {config['hostname']}") print(f"resource config file: {config['resources']}") + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + asyncio.run(amain(config), debug=bool(args.debug)) if reexec: