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

How can i perform some actions after the program ends?

asked 2018-11-27 22:22:42 -0500

kolyazoloto gravatar image

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?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2018-11-28 06:27:33 -0500

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
edit flag offensive delete link more

Comments

Thank you.

kolyazoloto gravatar image kolyazoloto  ( 2018-11-28 20:33:38 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2018-11-27 21:40:52 -0500

Seen: 192 times

Last updated: Nov 28 '18