打印到类外的控制台

2024-06-26 04:01:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我搞不清楚这个。你知道吗

我有一个类,它将控制台打印到类的“内部”。我希望能够打印类的“外部”,以便我可以使用数据流进行其他事情。如何从下面的代码中获取流?你知道吗

from ws4py.client.threadedclient import WebSocketClient
import json

class FooClient(WebSocketClient):

    msg=0

    def opened(self):
        self.send(json.dumps({"One": "bah", "Two": "bah"}))

    def closed(self, code, reason=None):
        print "Closed down", code, reason

    def received_message(self, m):
        if len(m) == 175:
            self.close(reason='Remote server closed socket')
        msg = json.loads(str(m))
        #print msg 


ws = FooClient('wss://ws-feed.foobar.com', protocols=['http-only', 'chat'])
ws.connect()
ws.run_forever()

我尝试了许多不同的方法,但还没有理解实现这一目标的正确方法。从概念上讲,我想要:

    ws = FooClient('wss://ws-feed.foobar.com', protocols=['http-only', 'chat'])
    ws.connect()
    ws.run_forever()
    print msg

但显然这不起作用。你知道吗


Tags: importselfjsonwsdeffeedcodemsg
1条回答
网友
1楼 · 发布于 2024-06-26 04:01:25

为什么不在received_message()中打印消息?一旦您调用run_forever(),它只会在您的客户机死亡(或断开连接?)时返回。必须处理执行循环中的事件。你知道吗

run_forever()  > 
   code handling web-sockets  >
      event handlers <  do it here

在我看来,您真正想做的是在不同进程/线程或执行器的上下文中运行此代码,以便继续执行其他操作。你知道吗

看一看:https://docs.python.org/3/library/concurrent.futures.html

相关问题 更多 >