我有一个简单的python tkinter gui,只有几个按钮。当按下按钮时,我要做的就是启动Websocket连接并开始接收。我可以正常运行代码,但是一旦尝试将其放入线程中,我就会出错
RuntimeError: There is no current event loop in thread
因此,首先尝试:
import websockets
websocket = websockets.connect(uri, ssl = True)
websocket.recv()
我得到错误
"Connect object has no attribute 'recv'"
当我以不同的方式运行它时,这很奇怪我没有完全遵循文档
def run_websockets2(self):
async def hello():
uri = Websocket_Feed
# with websockets.connect(uri, ssl=True) as websocket:
socket = await websockets.connect(uri, ssl=True)
self.web_socket = socket
while self.running:
greeting = await socket.recv()
print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())
只要我仅调用“ websockets2()”,它就可以工作。但是如果我尝试去做
self.websocket_thread = threading.Thread(target=self.run_websockets2, args=())
self.websocket_thread.start()
我得到错误
RuntimeError: There is no current event loop in thread 'web_sockets'
当我使整个功能不同步时,我得到一个错误
def run_websockets(self):
uri = Websocket_Feed
# with websockets.connect(uri, ssl=True) as websocket:
socket = websockets.connect(uri, ssl=True)
self.web_socket = socket
while self.running:
greeting = socket.recv()
print(f"< {greeting}")
我收到错误RuntimeError:线程'web_sockets'中没有当前事件循环。在套接字上= websockets.connect(uri,ssl = True)
我不明白为什么我不能只是简单地在线程中运行这些非异步的。任何帮助是极大的赞赏
您在这里有几个不同的错误,这使图片有些混乱。首先,关于:
"Connect object has no attribute 'recv'"
...这只是说该websocket
对象没有调用任何方法recv
您遇到的主要问题是尝试run_websockets2()
从生成的线程调用。即从主线程调用此方法有效,但是从新线程调用此方法失败。
这是预期的行为。这是因为在生成的线程(即主线程以外的线程)中,未定义异步事件循环。但是为了方便起见,在主线程中定义了一个。因此asyncio知道您是从生成线程还是主线程中调用,并且行为有所不同。请参阅此答案以获取详细的移植信息。为什么asyncio.get_event_loop方法检查当前线程是否为主线程?
为了解决您的问题,您可以为每个产生的线程创建一个新的事件循环,以便代码变为:
event_loop = asyncio.new_event_loop()
event_loop.run_until_complete(hello())
代替
asyncio.get_event_loop().run_until_complete(hello())
或者,您可以将其存储event_loop
在一个公共位置,并允许所有产生的线程重用该事件循环。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句