From cbc5bf90c836b043482ed73738f56bd9e0a98e8a Mon Sep 17 00:00:00 2001 From: Chris Lalancette Date: Tue, 9 Jul 2024 18:36:44 +0000 Subject: [PATCH] Switch to using an rclpy context manager. This still manages the lifetime of rclpy, but uses less code to do so. Signed-off-by: Chris Lalancette --- .../test/launch_pytest/examples/check_node_msgs.py | 5 +---- .../launch_pytest/examples/executables/talker.py | 14 +++++--------- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/launch_pytest/test/launch_pytest/examples/check_node_msgs.py b/launch_pytest/test/launch_pytest/examples/check_node_msgs.py index 38eb0da5a..9428a7687 100644 --- a/launch_pytest/test/launch_pytest/examples/check_node_msgs.py +++ b/launch_pytest/test/launch_pytest/examples/check_node_msgs.py @@ -46,14 +46,11 @@ def generate_test_description(): @pytest.mark.launch(fixture=generate_test_description) def test_check_if_msgs_published(): - rclpy.init() - try: + with rclpy.init(): node = MakeTestNode('test_node') node.start_subscriber() msgs_received_flag = node.msg_event_object.wait(timeout=5.0) assert msgs_received_flag, 'Did not receive msgs !' - finally: - rclpy.shutdown() class MakeTestNode(Node): diff --git a/launch_pytest/test/launch_pytest/examples/executables/talker.py b/launch_pytest/test/launch_pytest/examples/executables/talker.py index 46cc60756..6d76a23f8 100644 --- a/launch_pytest/test/launch_pytest/examples/executables/talker.py +++ b/launch_pytest/test/launch_pytest/examples/executables/talker.py @@ -13,6 +13,7 @@ # limitations under the License. import rclpy +from rclpy.executors import ExternalShutdownException from rclpy.node import Node from std_msgs.msg import String @@ -34,17 +35,12 @@ def callback(self): def main(args=None): - rclpy.init(args=args) - - node = Talker() - try: - rclpy.spin(node) - except KeyboardInterrupt: + with rclpy.init(args=args): + node = Talker() + rclpy.spin(node) + except (KeyboardInterrupt, ExternalShutdownException): pass - finally: - node.destroy_node() - rclpy.shutdown() if __name__ == '__main__':