ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A
Ask Your Question

Python Spin Once Equivalent

asked 2013-12-13 12:56:33 -0500

atp gravatar image

updated 2014-01-28 17:06:37 -0500

ngrennan gravatar image

Is there an equivalent to spin_once (C++) in ROS for Python?

In C++ I have a loop with spin_once and during each iteration of the loop the code checks a couple of global variables for changes and then does some action based on the value of those global variables. The global variables are based on messages from other nodes' topics to which my C++ ROS node is subscribed. How would this code structure translate into Python?

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted

answered 2013-12-16 00:07:25 -0500

demmeln gravatar image

No, there is no spin_once in rospy. In rospy the subscriber's callbacks are executed in separate threads. Google quickly produces these old questions including answers:

To translate your loop from C++ you could either check periodically in a loop in the main thread, or check in each of the callbacks. Either way you likely need some thread synchronization.

edit flag offensive delete link more


Nabble doesn't work any longer, but I was able to find this one (it's nice the nabble url contained some searchable text, though this once has a date encoded)

You don't need spinOnce in rospy as the I/O is multithreaded. You can use the Rate object to contrain the rate of processing, though it does not have the same effect as spinOnce in roscpp. - Ken

lucasw gravatar image lucasw  ( 2022-01-12 10:48:03 -0500 )edit

answered 2019-06-12 09:00:07 -0500

byque gravatar image

The rospy function wait_for_message() allowed me to receive one message from topic in Python.

edit flag offensive delete link more


Exactly what I wanted, thanks.

I have used below code:

msg = rospy.wait_for_message("/camera/depth/color/points", PointCloud2, timeout=None)
askkvn gravatar image askkvn  ( 2020-05-19 03:24:48 -0500 )edit

Please note that wait_for_message does the following internally: it subscribes to the topic, waits for a message, then unsubscribes. This is only useful if you want to get an odd message once in a while. Don't do this in a loop - it will stress the ros master and all nodes publishing on that topic, and you'll lose all the messages between unsubscribing and subscribing again.

Martin Günther gravatar image Martin Günther  ( 2020-10-02 03:37:38 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2013-12-13 12:56:33 -0500

Seen: 41,199 times

Last updated: Dec 16 '13