Declare Subscribers in a For Loop [closed]
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?
could you explain your "althought it does help" ?
Sure, I've got 5 objects in the dictionary and 2 or 3 or them will get through, usually, when I add the time.sleep in. The last one is always jumbled with one of the others though.
Please ask another question with a reproducible example if you'd like more help.
Well, first off, this post is over 9 months old and the project I was working on then is now over so it doesn't matter. Second, this is reproducible. All you have to do is attempt to declare subscribers in a for loop and it won't work.
I realize this was old and I was cleaning up. If this is actually a bug I'd like to have a test case to reproduce and ticket. You've asserted it "doesn't work" but what does that exactly mean? Nothing is delivered? Some things are miss delivered?
I created a very simple test program here: https://gist.github.com/tfoote/496139... and it appears to do the right thing with Subscriber creation inside a for loop.
So if I remember correctly, what happened was several of the subscribers in the for loop ended up looking at the same publisher. If you want to see the code in context, you can look here: https://github.com/tscheney/aimbot/bl... starting on line 64.
The code that didn't work is commented out and the there is code that replaced it below, not using a for loop, that did work.