سؤال

since I found out, that imaplib does not support a timeout, I tried to override the open() function. But without success. I do not really know what I should inherit (imaplib, or imaplib.IMAP4), because the modul also has code which is not included in the classes. Here is what I want to have:

    # Old
    def open(self, host = '', port = IMAP4_PORT):
            self.sock = socket.create_connection((host, port))
            [...]

    # New, what I want to have
    def open(self, host = '', port = IMAP4_port, timeout = 5):
            self.sock = socket.create_connection((host, port), timeout)
            [...]

I just copied the original lib and altered it, which worked, but I don't think that this is the way how things should be done.

Could someone please show me an elegant way how I could solve this problem?

Thanks in advance!

هل كانت مفيدة؟

المحلول

Okay, so I think I managed it. It was more a try and error than pure knowledge, but it works.

Here is what I did:

import imaplib
import socket

class IMAP4(imaplib.IMAP4):
""" Change imaplib to get a timeout """

    def __init__(self, host, port, timeout):
        # Override first. Open() gets called in Constructor
        self.timeout = timeout
        imaplib.IMAP4.__init__(self, host, port)


    def open(self, host = '', port = imaplib.IMAP4_PORT):
        """Setup connection to remote server on "host:port"
            (default: localhost:standard IMAP4 port).
        This connection will be used by the routines:
            read, readline, send, shutdown.
        """
        self.host = host
        self.port = port
        # New Socket with timeout. 
        self.sock = socket.create_connection((host, port), self.timeout)
        self.file = self.sock.makefile('rb')


def new_stuff():
    host = "some-page.com"
    port = 143
    timeout = 10
    try:
        imapcon = IMAP4(host, port, timeout)
        header = imapcon.welcome
    except Exception as e:  # Timeout or something else
        header = "Something went wrong here: " + str(e)
    return header


print new_stuff()

Maybe this is helpful for others

نصائح أخرى

Though imaplib doesn't support timeout, you can set a default timeout on the socket which will be used when any socket connection is established.

socket.setdefaulttimeout(15)

ex:

import socket
def new_stuff():
    host = "some-page.com"
    port = 143
    timeout = 10
    socket.setdefaulttimeout(timeout)
    try:
        imapcon = imaplib.IMAP4(host, port)
        header = imapcon.welcome
    except Exception as e:  # Timeout or something else
        header = "Something went wrong here: " + str(e)
    return header
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top