Python - 等待变量更改

Han*_*pan 5 python twitter callback websocket

我有一个Python脚本,它打开一个websocket到Twitter API,然后等待.当事件通过amq传递给脚本时,我需要打开一个新的websocket连接,并在注册新连接后立即关闭旧连接.

它看起来像这样:

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()
Run Code Online (Sandbox Code Playgroud)

我试图弄清楚如何建立一个'回调',以便通知我的脚本何时建立新的连接.TwitterStream类有一个我可以引用的"is_running"布尔变量,所以我想的可能是:

while not new_stream.is_running:
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

但它似乎有点混乱.有谁知道更好的方法来实现这一目标?

Ass*_*vie 7

繁忙的循环不是正确的方法,因为它显然浪费CPU.相反,有一些线程构造可以让您传达此类事件.例如,请参阅:http://docs.python.org/library/threading.html#event-objects


Tom*_* C. 5

这是线程事件的示例:

import threading
from time import sleep

evt = threading.Event()
result = None
def background_task(): 
    global result
    print("start")
    result = "Started"
    sleep(5)
    print("stop")
    result = "Finished"
    evt.set()
t = threading.Thread(target=background_task)
t.start()
# optional timeout
timeout=3
evt.wait(timeout=timeout)
print(result)
Run Code Online (Sandbox Code Playgroud)