Python - 等待变量更改 [英] Python - Waiting for variable change

查看:44
本文介绍了Python - 等待变量更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

看起来像这样:

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"布尔变量,所以我在想可能是这样的:

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?

推荐答案

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

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

这篇关于Python - 等待变量更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆