0
$\begingroup$

Rosanswers logo

Hello. How can i perform some actions after the program ends? I tried to use ROSInterruptException but it did not work.

!/usr/bin/env python
import rospy
from std_msgs.msg import String

def talker():

    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

try:
    talker()
except rospy.ROSInterruptException:
    rospy.loginfo("TEST")

And when I do Ctrl+C the "TEST" line does not appear. What have I done wrong? Why the exception does not work?


Originally posted by kolyazoloto on ROS Answers with karma: 3 on 2018-11-27

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

You can register a callback for the shutdown hook in rospy as described here.

This shutdown even is called before the ros system closes so you should still be able to write log messages. Your code will look something like this:

!/usr/bin/env python
import rospy
from std_msgs.msg import String

def talker():

    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

def my_shutdown_handler():
  print "shutdown time!"
  rospy.loginfo("test shutdown.")

try:
    rospy.on_shutdown(my_shutdown_handler)
    talker()
except rospy.ROSInterruptException:
    pass

Originally posted by PeteBlackerThe3rd with karma: 9529 on 2018-11-28

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by kolyazoloto on 2018-11-28:
Thank you.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.