Python - 等待变量变化

14 投票
2 回答
37158 浏览
提问于 2025-04-17 04:41

我有一个Python脚本,它会打开一个与Twitter API的websocket连接,然后就一直等待。当有事件通过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()

我在想怎么设置一个“回调”,这样可以在新连接建立时通知我的脚本。TwitterStream类里面有一个“is_running”的布尔变量,我可以用它,所以我在想可以这样做:

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

不过这样看起来有点乱。有没有人知道更好的方法来实现这个?

2 个回答

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)
13

忙等待循环并不是一个好的方法,因为这样会浪费计算机的处理能力。其实有一些线程的工具可以让你更好地处理这些事件。你可以看看这个链接了解更多信息: http://docs.python.org/library/threading.html#event-objects

撰写回答