Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
Hanpan Avatar asked Feb 10 '26 06:02

Hanpan


1 Answers

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

like image 109
Assaf Lavie Avatar answered Feb 12 '26 20:02

Assaf Lavie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!