我有一个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)
但它似乎有点混乱.有谁知道更好的方法来实现这一目标?