【问题标题】:Trouble with Async threads and event loops in pythonpython中异步线程和事件循环的问题
【发布时间】:2021-05-30 23:14:45
【问题描述】:

我无法理解这个由这里的代码块生成的错误:

def websock():

    while True:

        async def WebSocketserver(websocket, path):
        
            global message
            global logmsg
        
            while True:
                Rxdata = await websocket.recv()
                # construct the message that we will log
                data = json.loads(Rxdata)
                command = data.get('Message')
                person = data.get('Name')
                commandTime = data.get('Time')
                message = command
                logmsg = [person, message, str(commandTime), "allowed", "console"]
                print(f" {person} on the controller: {command}")
                await websocket.send("200")

        start_server = websockets.serve(WebSocketserver, Host, SocketPort)

        asyncio.get_event_loop().run_until_complete(start_server)
        asyncio.get_event_loop().run_forever()

这给了我以下错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\twitch\lib\threading.py", line 954, in _bootstrap_inner       
    self.run()
  File "C:\ProgramData\Anaconda3\envs\twitch\lib\threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "D:\CloudStorage\OneDrive - Personal\OneDrive\Projects-R2D2\scripts-twitchPlays\code\TwitchPlays_2\TwitchPlaysCode.py", line 276, in websock
    start_server = websockets.serve(WebSocketserver, Host, SocketPort)
  File "C:\ProgramData\Anaconda3\envs\twitch\lib\site-packages\websockets\legacy\server.py", line 999, in __init__
    loop = asyncio.get_event_loop()
  File "C:\ProgramData\Anaconda3\envs\twitch\lib\asyncio\events.py", line 642, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-1'.

没有事件循环是什么意思? while 语句不应该涵盖这一点吗?我从这里借用这个理解:https://medium.com/@tigranbs/concurrency-vs-event-loop-vs-event-loop-concurrency-eb542ad4067b 但我现在很迷茫。

【问题讨论】:

    标签: python websocket python-asyncio


    【解决方案1】:

    经过进一步研究,我想我已经找到了一个可行的答案:

    def websock():
    
        async def WebSocketserver(websocket, path):
        
            global message
            global logmsg
        
            while True:
                Rxdata = await websocket.recv()
                # construct the message that we will log
                data = json.loads(Rxdata)
                command = data.get('Message')
                person = data.get('Name')
                commandTime = data.get('Time')
                message = command
                logmsg = [person, message, str(commandTime), "allowed", "console"]
                print(f" {person} on the controller: {command}")
                await websocket.send("200")
    
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
    
        start_server = websockets.serve(WebSocketserver, Host, SocketPort)
    
        loop.run_until_complete(start_server)
        loop.run_forever()
    

    这样写函数是有道理的——为什么在我们调用 webserver serve 方法之前没有事件循环,现在它可以通过事件循环为 web 服务器提供服务——所以创建一个事件循环——将它设置为正确的异步循环,然后将其设置为运行直到完成(这有点永远,因为循环为真)并将其设置为永远运行应该使它运行。至少这段代码没有给我错误——所以如果有人(可以说更熟悉这个)可以确认这种思维模式——那就太好了!

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 2019-02-17
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 2023-03-08
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多