【问题标题】:Override open() in imaplib覆盖 imaplib 中的 open()
【发布时间】:2013-05-29 08:49:27
【问题描述】:

自从我发现imaplib 不支持超时后,我尝试覆盖open() 函数。但没有成功。我真的不知道我应该继承什么(imaplibimaplib.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)
            [...]

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

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

提前致谢!

【问题讨论】:

    标签: python oop imaplib


    【解决方案1】:

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

    这是我所做的:

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

    也许这对其他人有帮助

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 2014-05-05
        • 1970-01-01
        • 1970-01-01
        • 2022-11-09
        • 1970-01-01
        • 2011-06-11
        • 2012-01-28
        • 2012-07-18
        • 1970-01-01
        相关资源
        最近更新 更多