Skip to content

Commit

Permalink
Add top-level try_shutdown method. (#1302)
Browse files Browse the repository at this point in the history
I noticed that this was needed when trying to convert some
of the examples over to the context manager.  They currently
throw an exception because the signal handler does the
shutdown, and then leaving the context tries to do it
again.

This is also more symmetric with what shutdown() does,
in that it also uninstalls signal handlers.

Signed-off-by: Chris Lalancette <[email protected]>
  • Loading branch information
clalancette authored Jun 20, 2024
1 parent cef4ce9 commit ee22148
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions rclpy/rclpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
from rclpy.utilities import get_rmw_implementation_identifier # noqa: F401
from rclpy.utilities import ok # noqa: F401 forwarding to this module
from rclpy.utilities import shutdown as _shutdown
from rclpy.utilities import try_shutdown # noqa: F401
from rclpy.utilities import try_shutdown as _try_shutdown

# Avoid loading extensions on module import
if TYPE_CHECKING:
Expand Down Expand Up @@ -100,7 +100,7 @@ def __exit__(
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
shutdown(context=self.context, uninstall_handlers=self.installed_signal_handlers)
try_shutdown(context=self.context, uninstall_handlers=self.installed_signal_handlers)


def init(
Expand Down Expand Up @@ -171,6 +171,32 @@ def shutdown(
uninstall_signal_handlers()


def try_shutdown(
*,
context: Optional[Context] = None,
uninstall_handlers: Optional[bool] = None
) -> None:
"""
Shutdown a previously initialized context if not already shutdown.
This will also shutdown the global executor.
:param context: The context to invalidate. If ``None``, then the default context is used
(see :func:`.get_default_context`).
:param uninstall_handlers:
If `None`, signal handlers will be uninstalled when shutting down the default context.
If `True`, signal handlers will be uninstalled.
If `False`, signal handlers won't be uninstalled.
"""
_try_shutdown(context=context)
if (
uninstall_handlers or (
uninstall_handlers is None and (
context is None or context is get_default_context()))
):
uninstall_signal_handlers()


def create_node(
node_name: str,
*,
Expand Down

0 comments on commit ee22148

Please sign in to comment.