如何关闭和重启 Python websocket 线程?

问题描述 投票:0回答:1

我试图关闭并重新启动一个 websocket 线程但不能,代码如下:

import threading
import websocket


pair = 'XRPMYR'

# Create a restart flag
to_restart_wsl[pair] = False

def wsl_thread(pair):
    wsl_url = f"wss://ws.luno.com/api/1/stream/{pair}"
    while not to_restart_wsl[pair]:
        try:
            wsl = websocket.WebSocketApp(wsl_url, on_open=lambda ws: wsl_open(ws, pair), on_message=lambda ws, msg: wsl_message(ws, msg, pair))
            print(f"{pair} Luno websocket feed started.")
            wsl.run_forever()
        except Exception as e:
            print(e)
        time.sleep(5)


# Create and start the thread
luno_thread = threading.Thread(target=wsl_thread, args=(pair,), name=pair)
luno_thread.start()

# Stop the thread
to_restart_wsl[pair] = True
luno_thread.join()

# Restart the thread
to_restart_wsl[pair] = False
luno_thread = threading.Thread(target=wsl_thread, args=(pair,))
luno_thread.start()

我怀疑这是因为在

wsl_thread()
内部,
wsl.run_forever()
一直在运行并且没有完成循环来检查
to_restart_wsl[pair]
,所以它永远不会停止。我怎样才能真正停止 websocket 线程以重新启动它?

我尝试寻找杀死线程模块内线程的方法,但没有办法做到这一点,唯一的方法是

Thread.join()
,它将等待线程完成,但线程永远不会完成,因为
run_forever()
永远运行.

编辑: 我尝试创建一个单独的线程,使用

.close()
尝试关闭相同的 websocket 连接,希望它会关闭并且
wsl_thread()
将退出,然后重新启动它。下面的代码,将检查并稍后尝试看看它是否有效。

编辑4: 下面的代码不起作用,它不会关闭相同的 websocket 连接,而是打开一个新实例并关闭它,我已经在下面的答案中找到了解决方案

def close_wsl(pair):
    wsl_url = f"wss://ws.luno.com/api/1/stream/{pair}"
    try:
        wsl = websocket.WebSocketApp(wsl_url)
        wsl.close()
        error_log(f"{pair} websocket feed closed, it should auto restart.")
    except Exception as e:
        error_log(e)

to_restart_wsl[pair] = True
close_wsl(pair)
luno_thread.join()

to_restart_wsl[pair] = False
luno_thread = threading.Thread(target=wsl_thread, args=(pair,))
luno_thread.start()
python websocket python-multithreading
1个回答
0
投票

设法找出解决方案,在

to_restart_wsl[pair]
函数中添加
wsl_message
标志,当标志变为True时它将运行
.close()
方法然后关闭wsl连接,此后
.run_forever()
wsl_thread 
将再次重新连接

import threading
import websocket


pair = 'ETHMYR'

# create a restart flag
to_restart_wsl[pair] = False

def wsl_thread(pair):
    wsl_url = f"wss://ws.luno.com/api/1/stream/{pair}"
    while True:
        try:
            wsl = websocket.WebSocketApp(wsl_url, on_open=lambda wsl: wsl_open(wsl, pair), on_message=lambda wsl, msg: wsl_message(wsl, msg, pair))
            print(f"{pair} Luno websocket feed started.")
            wsl.run_forever()
        except Exception as e:
            print(e)
        time.sleep(3)

def wsl_message(wsl, msg, pair):
    # do something with msg
    if to_restart_wsl[pair]:
        wsl.close()
        to_restart_wsl[pair] = False

# create and start the thread
luno_thread = threading.Thread(target=wsl_thread, args=(pair,), name=pair)
luno_thread.start()

# restart the thread
to_restart_wsl[pair] = True
© www.soinside.com 2019 - 2024. All rights reserved.