相关疑难解决方法(0)

python 协程超时

如何让协程因超时而停止?

我不明白为什么 asyncio.wait_for() 对我不起作用。我有这样一段代码(计划实现 telnet 客户端):

def expect(self, pattern, timeout=20): 
    if type(pattern) == str:
        pattern = pattern.encode('ascii', 'ignore')        
    return self.loop.run_until_complete(asyncio.wait_for(self.asyncxpect(pattern), timeout))

async def asyncxpect(self, pattern): #receives data in a cumulative way until match is found
    regexp = re.compile(b'(?P<payload>[\s\S]*)(?P<pattern>%s)' %pattern)
    self.buffer = b''
    while True:
        # add timeout
        # add exception handling for unexpectedly closed connections
        data = await self.loop.sock_recv(self.sock, 10000) 
        self.buffer += data
        m = re.match(regexp, self.buffer)
        if m:
            payload = m.group('payload')
            match = m.group('pattern')
            return payload, match 
Run Code Online (Sandbox Code Playgroud)

正如我所认为的,这段代码在某个时刻(在等待语句中)将控制权返回给事件循环。我认为当没有更多数据可以接收时应该发生这种情况。如果事件循环有控制权,它可以超时停止。

但是,如果服务器没有发送任何有用的(匹配的)我的代码就会在这个循环中绊倒,就在等待点。 …

python coroutine python-sockets python-asyncio

2
推荐指数
1
解决办法
2345
查看次数