ROS1转ROS2:求RCLPY中rospy.is_shutdown()与rate.sleep()替代方法
Hey there! Let's get that ROS1 loop converted to ROS2 with rclpy sorted out for you. You're already halfway there with the create_rate replacement—let's cover the rest and give you full working code examples.
First, let's break down the equivalents you're missing:
rospy.is_shutdown(): In rclpy, the direct replacement isrclpy.ok(). This checks if the ROS2 context is still active (i.e., hasn't been shut down via Ctrl+C or other means), just like the ROS1 method.rate.sleep(): Good news—this works exactly the same way in ROS2! Once you create a rate object withnode.create_rate(2), callingrate.sleep()will handle the timing to maintain your 2Hz loop, just like before.
Here's the full converted script-style code that matches your original ROS1 logic:
#!/usr/bin/env python3 import rclpy from rclpy.node import Node def main(args=None): # Initialize the ROS2 context (equivalent to rospy.init_node) rclpy.init(args=args) # Create your node node = Node("simple_node") # Create the 2Hz rate object rate = node.create_rate(2) # The loop that runs until shutdown while rclpy.ok(): print("Help me body, you are my only hope") # Maintain the 2Hz frequency rate.sleep() # Clean up resources node.destroy_node() rclpy.shutdown() if __name__ == "__main__": main()
If you're using a class-based node (which is more aligned with ROS2 best practices), here's how that would look:
#!/usr/bin/env python3 import rclpy from rclpy.node import Node class SimpleNode(Node): def __init__(self): super().__init__("simple_node") # Create the rate object inside the node class self.rate = self.create_rate(2) def run_loop(self): while rclpy.ok(): print("Help me body, you are my only hope") self.rate.sleep() def main(args=None): rclpy.init(args=args) simple_node = SimpleNode() simple_node.run_loop() simple_node.destroy_node() rclpy.shutdown() if __name__ == "__main__": main()
As a bonus, ROS2 encourages using timers instead of explicit loops + rate objects for periodic tasks. This is a more asynchronous approach that fits better with ROS2's architecture. Here's how you could rewrite your logic with a timer:
#!/usr/bin/env python3 import rclpy from rclpy.node import Node class SimpleNode(Node): def __init__(self): super().__init__("simple_node") # Create a timer that triggers every 0.5 seconds (2Hz) self.timer = self.create_timer(0.5, self.timer_callback) def timer_callback(self): print("Help me body, you are my only hope") def main(args=None): rclpy.init(args=args) simple_node = SimpleNode() # Spin the node to keep it alive and process timer callbacks rclpy.spin(simple_node) simple_node.destroy_node() rclpy.shutdown() if __name__ == "__main__": main()
This timer approach eliminates the need for manual loop management—ROS2 handles the timing and callback execution for you.
内容的提问来源于stack exchange,提问作者skyhigh1312




