为什么我的except子句永远不会捕获gevent超时异常?

时间:2013-01-17 05:36:10

标签: python timeout gevent

当我尝试telnet到服务器时,代码永远不会到达print 'never reach1'print 'never reach2'行。

import sys, signal
from gevent.server import StreamServer
from gevent.pool import Pool
from gevent import monkey
import gevent
from gevent import Timeout
import random

class SocketPool(object):

    def __init__(self):
        self.pool = Pool(1000)

    def listen(self, socket):
        while True:
            line = socket.recv(1024)
            print line

    def add_handler(self, socket, address):
        if self.pool.full():
            raise Exception("At maximum pool size")
        else:
            self.pool.spawn(self.listen, socket)
            gevent.spawn(self.wait).join()

    def wait(self):
        try:
            timeout = Timeout(1)
            timeout.start()
        except Timeout:
            print 'never reach1'
        except:
            print 'never reach2'

    def shutdown(self): self.pool.kill()

def signal_handler(signal, frame): sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
monkey.patch_all()
sockPool = SocketPool()
server = StreamServer(('127.0.0.1', 5000), sockPool.add_handler)
server.serve_forever()

1 个答案:

答案 0 :(得分:2)

正如您从documentation

中看到的那样
timeout = Timeout(seconds, exception)
timeout.start()
try:
    ...  # exception will be raised here, after *seconds* passed since start() call
finally:
    timeout.cancel()

因此,您的try块已完全执行,因此无法捕获异常。 您应该放置类似while循环或需要至少1秒钟的计算来查看异常。

如果你想制作一个不使用CPU而只是“睡觉”的方法,我建议使用简单的time.sleep而不是Timeout