【发布时间】:2016-05-24 09:14:21
【问题描述】:
我正在尝试将值更新为无限循环,而不退出循环。此值作为参数从 WebSocket 客户端发送。我的问题是:如何更新无限循环内的值?
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
print('new connection')
clients.append(self)
self.write_message("connected")
def on_message(self, message):
print('tornado received from client: %s' % message)
new_message =""
while True:
new_message=self.updateMessage(message)
print(new_message)
def updateMessage(self, message):
return(message)
def main():
parse_command_line()
app = tornado.web.Application(
[
(r"/ws", WebSocketHandler)
],
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static")
)
app.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
我希望循环内的打印消息使用 on_message 函数中接收的新消息进行更新。如果我删除 while 循环,将打印新消息(Websocket 客户端发送的新值)。但是现在它永远只打印第一条消息(值),因为循环。
【问题讨论】:
-
我认为将你的代码提炼成一个简单的例子来捕捉你的问题的本质会很好,这听起来像是一个基本的python问题。这种方式更通用(即对未来的读者有帮助),我们不需要解析大量的 WebSocket 代码。
-
你的缩进被破坏了。由于缩进在 python 中在语法上很重要,所以在你修复它之前讨论这个是没有用的。