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

时间:2021-05-30 23:14:45

标签: python websocket python-asyncio

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

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 但我在这一点上很迷茫。

1 个答案:

答案 0 :(得分:0)

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

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 服务器提供服务——所以创建一个事件循环 - 将它设置为正确的 asyncio 循环,然后将其设置为运行直到完成(这有点永远,因为循环为真)并将其设置为永远运行应该让它运行。至少这段代码不会给我错误 - 所以如果有人(可以说更熟悉这个)可以确认这种思维模式 - 那会很棒!

相关问题