Python上的Pusher永远运行

Python上的Pusher永远运行,python,sockets,websocket,pusher,Python,Sockets,Websocket,Pusher,我正在学习在一个新项目中使用WebSocket。我想监控通过多个不同套接字连接发送的实时消息流。碰巧有一个套接字API使用了它。我喜欢在python中工作,所以我发现。对于我正在使用的其他连接 所以我的问题是,除了示例中的while True:循环之外,还有更好的方法让pusher客户端永远运行吗 ... global pusher # We can't subscribe until we've connected, so we use a callback handler # to sub

我正在学习在一个新项目中使用WebSocket。我想监控通过多个不同套接字连接发送的实时消息流。碰巧有一个套接字API使用了它。我喜欢在python中工作,所以我发现。对于我正在使用的其他连接

所以我的问题是,除了示例中的
while True:
循环之外,还有更好的方法让pusher客户端永远运行吗

...
global pusher

# We can't subscribe until we've connected, so we use a callback handler
# to subscribe when able
def connect_handler(data):
    channel = pusher.subscribe('mychannel')
    channel.bind('myevent', callback)

pusher = pusherclient.Pusher(appkey)
pusher.connection.bind('pusher:connection_established', connect_handler)
pusher.connect()

while True:
    # Do other things in the meantime here...
    time.sleep(1)
这是可行的,但似乎真的吸CPU。使用
websocket客户端
包,pypi页面上有一个示例显示了如何永远运行客户端:

...
#omitted function definitions
if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()
我测试了这两种类型的代码,它们都可以工作,但是websocket客户端似乎比Pusher客户端使用更少的CPU。因为我需要同时打开多个客户端,所以我真的很想节省资源。我在想,应该有一种比
while True
循环更好、更漂亮、更便宜的方法让套接字保持活力。有人知道好的技巧吗


谢谢

默认情况下,
推送程序
客户端是一个deamon,这意味着底层线程在后台运行,不会阻止主python线程关闭

至少在较新的版本(例如:0.6.0b2)中,有一个名为
daemon
的初始化参数,您可以将其设置为
False
,这样您就不需要在
过程中退出

例如:

pusher = pusherclient.Pusher(appkey, daemon=False)
pusher.connection.bind('pusher:connection_established', connect_handler)
pusher.connect()

# No need for a while True as the underlying non-daemon thread will prevent the process 
# from dying automatically.

默认情况下,
Pusher
客户端是一个deamon,这意味着底层线程在后台运行,它不会阻止主python线程关闭

至少在较新的版本(例如:0.6.0b2)中,有一个名为
daemon
的初始化参数,您可以将其设置为
False
,这样您就不需要在
过程中退出

例如:

pusher = pusherclient.Pusher(appkey, daemon=False)
pusher.connection.bind('pusher:connection_established', connect_handler)
pusher.connect()

# No need for a while True as the underlying non-daemon thread will prevent the process 
# from dying automatically.

现在还不清楚你的目标是什么,以及会发生什么。插座关上了吗?还不清楚您使用的是什么库-听起来您使用两个不同的库作为客户连接到Pusher。谢谢您的评论,我想这不是很清楚。我使用2个库同时连接到2个(或更多)websocket提要。我想这不是一个好问题,我想我会结束它。不清楚你的目标是什么,以及会发生什么。插座关上了吗?还不清楚您使用的是什么库-听起来您使用两个不同的库作为客户连接到Pusher。谢谢您的评论,我想这不是很清楚。我使用2个库同时连接到2个(或更多)websocket提要。我想这不是一个好问题,我想我会结束它。