Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Declare Subscribers in a For Loop

I'd like to be able to declare subscriptions in a for loop so that my code is more dynamic. In Python I've got a dynamically created dictionary full of a custom class that includes a msg callback function as one of it's methods. Essentially I'm trying to run this code:

for name in dictionary.iteritems():
rospy.Subscriber(/path/[name], Pose2D, lambda msg: dictionary[name].import_msg(msg))

However, it doesn't work. The subscriptions all get jumbled together on whatever happens to be the last one run through. After reading around, it seems like it takes some amount of time for the subscriptions to get connected properly, which is why I guess it isn't working. Weirdly though, even if I add a time.sleep(3) etc after the subscriber line inside the for loop, it doesn't clear up the issue, although it does help. In fact, no amount of seconds waited seems to clear up the issue. Is there anyway that I can do this?