【问题标题】:Python - Waiting for variable changePython - 等待变量更改
【发布时间】:2011-10-20 12:47:40
【问题描述】:

我有一个 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)

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

【问题讨论】:

标签: python callback twitter websocket


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是一个线程事件的例子:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多