2

因为我发现imaplib它不支持超时,所以我试图覆盖该open()函数。但没有成功。我真的不知道我应该继承什么(imaplib,或imaplib.IMAP4),因为模块也有不包含在类中的代码。这是我想要的:

    # 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)
            [...]

我只是复制了原始库并对其进行了更改,这很有效,但我认为这不是应该做的事情。

有人可以告诉我一个优雅的方式来解决这个问题吗?

提前致谢!

4

2 回答 2

4

好的,所以我想我做到了。这比纯粹的知识更像是一次尝试和错误,但它确实有效。

这是我所做的:

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()

也许这对其他人有帮助

于 2013-06-04T06:34:59.897 回答
2

虽然 imaplib 不支持超时,但您可以在套接字上设置默认超时,该超时将在任何套接字连接建立时使用。

socket.setdefaulttimeout(15)

前任:

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
于 2013-11-12T14:26:19.273 回答