From f7dd8077705ee63b32e557f279f3021797fc8ce8 Mon Sep 17 00:00:00 2001 From: Chris Lalancette Date: Mon, 22 Jul 2024 07:49:17 -0400 Subject: [PATCH] Fix a bug when using multiple rclpy.init context managers. (#1314) That is, if you call rclpy.init as a context manager within the same process, and using the default context, it currently fails. That is because you cannot reinitialize (call init) on a Context object once it has been shutdown. Instead, force try_shutdown to replace the global context object with a new one on rclpy.init shutdown by passing a None. Signed-off-by: Chris Lalancette --- rclpy/rclpy/__init__.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/rclpy/rclpy/__init__.py b/rclpy/rclpy/__init__.py index 7ad9b8630..f57b14a65 100644 --- a/rclpy/rclpy/__init__.py +++ b/rclpy/rclpy/__init__.py @@ -100,7 +100,12 @@ def __exit__( exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: - try_shutdown(context=self.context, uninstall_handlers=self.installed_signal_handlers) + # The Context class can only be initialized once. Thus when using the default context, + # we have to destroy it every time we are done using it and create a new one. + # utilities.try_shutdown will only replace the default context if we pass 'None', so make + # sure to do that for the default context. + shutdown_context = None if self.context is get_default_context() else self.context + try_shutdown(context=shutdown_context, uninstall_handlers=self.installed_signal_handlers) def init(