Python: roslaunch KeyboardInterrupt exception not caught try---catch
I'm using roslaunch to launch several nodes that do some calculations. I want to print some variables continuously into a file. Part of the code looks like this:
class Agent:
def __init__(self, var1, ...):
filename = 'stdout_' + str(ID)
self.stdout_log = open(filename, 'w')
## ROS Topics and Services ################################################
###########################################################################
rospy.init_node('agent', anonymous=True)
myservice = '/serve'
srv = rospy.Service(myservice, Service_One, self.handle_serve)
self.publish_global = rospy.Publisher('msgs', Message_Type, queue_size=200)
rospy.Subscriber('trigger', Message_Type, self.callback)
###########################################################################
if __name__ == '__main__':
agent = Agent(var1,...)
try:
while True:
time.sleep(1)
print 'stuff'
agent.stdout_log.write('stuff')
except rospy.ROSInterruptException:
pass
finally:
agent.stdout_log.close()
If I give ctrl-c from the terminal window where I have exectued roslaunch, the file is created but there's nothing in it. After some trials, I suspect that it is because the file doesn't get to close. I try to ctrl-c the nodes themselves, but it doesn't work. If I remove the ros related declarations in __init__ then I can stop the node with ctrl-c. What can I do?