我有一个使用websockets的python程序:
def main():
ws = websocket.WebSocketApp("ws://foo.com/", on_message = on_ws_message)
ws.on_open = on_ws_open
ws.run_forever()
anobject = AnObject.foo()
def on_ws_open(ws):
ws.send('bar')
def on_ws_message(ws,message):
print message
我希望能够从anobject
函数中调用on_ws_message()
的方法,该函数会自动调用并进行线程化。我该怎么做?
答案 0 :(得分:1)
使用OOP:
class WhatEver(object):
def __init__(self):
self.ws = websocket.WebSocketApp("ws://foo.com/", on_message = self.on_ws_message)
self.ws.on_open = self.on_ws_open
self.anobject = AnObject()
def rin_forever(self):
self.ws.run_forever()
def on_ws_open(self, ws):
self.anobject.foo()
ws.send('bar')
def on_ws_message(self, ws,message):
print message
def main():
ws=WhatEver()
ws.run_forever()