首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重写imaplib中的open()

重写imaplib中的open()
EN

Stack Overflow用户
提问于 2013-06-03 16:30:43
回答 2查看 942关注 0票数 2

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

代码语言:javascript
复制
    # 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)
            [...]

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

有没有人能告诉我一个优雅的方法来解决这个问题?

提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-06-04 14:35:00

好吧,我想我成功了。与其说是纯粹的知识,不如说是一次尝试和错误,但它是有效的。

下面是我所做的:

代码语言:javascript
复制
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()

也许这对其他人有帮助。

票数 4
EN

Stack Overflow用户

发布于 2013-11-12 22:26:19

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

代码语言:javascript
复制
socket.setdefaulttimeout(15)

例如:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16892737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档