Robotics StackExchange | Archived questions

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?

Asked by thomascheney on 2017-02-23 09:05:22 UTC

Comments

could you explain your "althought it does help" ?

Asked by TTDM on 2017-02-23 09:31:28 UTC

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.

Asked by thomascheney on 2017-02-23 10:54:30 UTC

Please ask another question with a reproducible example if you'd like more help.

Asked by tfoote on 2017-11-26 18:19:32 UTC

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.

Asked by thomascheney on 2017-11-27 00:06:58 UTC

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?

Asked by tfoote on 2017-11-27 02:58:33 UTC

I created a very simple test program here: https://gist.github.com/tfoote/496139213ff8904fc00c65274e3fdd81 and it appears to do the right thing with Subscriber creation inside a for loop.

Asked by tfoote on 2017-11-27 02:59:25 UTC

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/blob/master/src/aimbot/scripts/Team.py starting on line 64.

Asked by thomascheney on 2017-11-28 00:57:33 UTC

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.

Asked by thomascheney on 2017-11-28 00:58:23 UTC

Answers