python 中的异步线程和事件循环出现问题

Trouble with Async threads and event loops in python

我无法理解此代码块生成的错误:

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 但此时我很迷茫。

经过进一步研究,我认为我找到了一个可能有效的答案:

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()

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