ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
5

How do you implement a rospy KeyboardInterrupt without killing the node?

asked 2016-07-20 17:45:06 -0500

M@t gravatar image

updated 2016-07-20 20:27:06 -0500

I want to run a process in a while loop that prints to screen, and exit the while loop by pressing a key or 'Ctrl+C'. But I don't want the same key press to also kill the ros node - I just want to exit the loop. In python you can use KeyboardInterrupt like so:

import time     

while True:
    try:
        print 'Help! Im stuck in a while loop! Press Ctrl+C to save me!'
        time.sleep(0.5)
    except KeyboardInterrupt:
        break

do_other_stuff()

But this doesn't work in a ROS node, and I assume it's because rospy handles the 'Ctrl+C' command in a slightly different way (but please correct me if I'm wrong).

I've tried the ROS equivalent, which replaces KeyboardInterrupt with rospy.ROSInterruptException but this doesn't work either - ROS simply never acknowledges the 'Ctrl+C' command. I've also tried checking for rospy.is_shutdown() in the while loop, as per this question. But this kills the node outright, so I can't continue running other functions or run the while loop again.

Does anyone have a way of achieving this? Or does one of my methods work but I've got the syntax wrong?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
7

answered 2016-07-20 17:52:35 -0500

ahendrix gravatar image

rospy sets up an interrupt handler for SIGINT (ctrl-C), and uses that to trigger shutdown of ROS.

If you don't want rospy to shut down when your program gets SIGINT, you should pass the disable_signals argument to rospy.init_node(), as described in rospy initialization and shutdown:

rospy.init_node('my_node', disable_signals=True)

You will then be able to do your own handling of SIGINT (or KeyboardInterrupt).

edit flag offensive delete link more

Comments

Yeap, that did the trick! As usual I read the right documentation but not thoroughly enough. The rospy exceptions still don't work, but setting disable_signals=True lets you deal with the interrupt as normal, just using KeyboardInterrupt Thanks again ahendrix!

M@t gravatar image M@t  ( 2016-07-20 20:30:43 -0500 )edit
3

answered 2022-06-29 16:13:05 -0500

If someone ends up here searching for how to that in ROS2 the key is:

rclpy.init(args=args, signal_handler_options=SignalHandlerOptions.NO)

don't forget import:

from rclpy.signals import SignalHandlerOptions

edit flag offensive delete link more

Comments

thank you!

minhaj gravatar image minhaj  ( 2022-07-28 17:26:25 -0500 )edit

Question Tools

2 followers

Stats

Asked: 2016-07-20 17:45:06 -0500

Seen: 7,206 times

Last updated: Jun 29 '22