首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pusher在Python上永远运行

Pusher在Python上永远运行
EN

Stack Overflow用户
提问于 2017-06-29 17:00:47
回答 1查看 623关注 0票数 1

我正在学习在一个新项目中使用websockets。我想监控来自多个不同套接字连接的实时消息流。碰巧有一个套接字API使用Pusher。我喜欢在python中工作,所以我找到了the pusherclient pacakge on pypi。对于其他连接,我使用the websocket-client package

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

代码语言:javascript
复制
...
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-client包,在pypi页面上有一个示例,它展示了如何永远运行客户端:

代码语言:javascript
复制
...
#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-client似乎比pusherclient使用了更少的CPU。因为我需要同时打开多个客户端,所以我真的想节省资源。我在想,应该有一种比while True循环更好、更漂亮、更便宜的方法来让套接字存活下来。有没有人知道一个好的技巧?

谢谢

EN

Stack Overflow用户

发布于 2018-08-15 02:26:20

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

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

示例:

代码语言:javascript
复制
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.
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44820641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档