Search code examples
pythonpython-2.7timeoutasyncore

asyncore.loop doesn't terminate when there are no more connections


I am following some example code to use asyncore here, only having set a timeout value for asyncore.loop as in the following full example:

import smtpd
import asyncore

class CustomSMTPServer(smtpd.SMTPServer):

    def process_message(self, peer, mailfrom, rcpttos, data):
        print 'Receiving message from:', peer
        print 'Message addressed from:', mailfrom
        print 'Message addressed to  :', rcpttos
        print 'Message length        :', len(data)
        return

server = CustomSMTPServer(('127.0.0.1', 1025), None)

asyncore.loop(timeout = 1)

I have expected that a timeout occurs after 1 second, but this is not the case. The code runs much longer for than one second. What am I missing here?


Solution

  • I really do not know if the timeout argument to asyncore.loop() really is meant to timeout the function call asyncore.loop() after the specified time, but here is a receipt to make that function timeout after a specified time (replacing the line with asyncore.loop() in the example code):

    import signal
    
    class TimeoutError(Exception): pass
    
    # define the timeout handler
    def handler(signum, frame):
        raise TimeoutError()
    
    # set the timeout handler and the signal duration
    signal.signal(signal.SIGALRM, handler)
    signal.alarm(1)
    try:
        asyncore.loop()
    except TimeoutError as exc:
        print "timeout"
    finally:
        signal.alarm(0)