Search code examples
pythoncallbacktwitterwebsocket

Python - Waiting for variable change


I have a Python script that opens a websocket to the Twitter API and then waits. When an event is passed to the script via amq, I need to open a new websocket connection and immediately close the old one just as soon as the new connection is registered.

It looks something like this:

stream = TwitterStream()
stream.start()

for message in broker.listen():
    if message:
        new_stream = TwitterStream()
        # need to close the old connection as soon as the 
        # new one connects here somehow
        stream = new_stream()

I'm trying to figure out how I'd establish a 'callback' in order to notify my script as to when the new connection is established. The TwitterStream class has a "is_running" boolean variable that I can reference, so I was thinking perhaps something like:

while not new_stream.is_running:
    time.sleep(1)

But it seems kind of messy. Does anyone know a better way to achieve this?


Solution

  • A busy loop is not the right approach, since it obviously wastes CPU. There are threading constructs that let you communicate such events, instead. See for example: http://docs.python.org/library/threading.html#event-objects