我想在Python中运行一个程序,它每秒通过Web套接字向Tornado服务器发送一条消息.我一直在websocket-client上使用这个例子;
此示例不起作用,因为ws.run_forever()将停止执行while循环.
有人能给我一个如何正确实现这个作为一个线程类的例子,我既可以调用send方法,也可以接收消息?
import websocket
import thread
import time
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
pass
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()
while True:
#do other actions here... collect data etc.
for i in range(100):
time.sleep(1)
ws.send("Hello %d" % i)
time.sleep(1)
Run Code Online (Sandbox Code Playgroud) 我对python中的sys.exit()感到很困惑.在python文档中,它说"退出Python"; 这是否意味着sys.exit()在python程序中调用时,进程将退出?如果是这样,下面的代码显示了不同的结果:
import sys
import time
import threading
def threadrun():
while(True):
time.sleep(1)
if __name__=="__main__":
t=threading.Thread(target=threadrun)
t.start()
sys.exit()
Run Code Online (Sandbox Code Playgroud)
在Linux中启动这个程序,结果不是python文档说的那个预期的,但仍然在系统中运行,那么sys.exit()真正做到了什么?