2013-06-03 64 views
2

因爲我發現,imaplib不支持超時,我試圖覆蓋open()函數。但沒有成功。我真的不知道我應該繼承什麼(imaplibimaplib.IMAP4),因爲modul還包含未包含在類中的代碼。 這裏是我想擁有的一切:覆蓋開放()在imaplib

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

我只是複製原來的lib和改變它,這工作,但我不認爲這是事物的方式應該怎麼做。

有人能告訴我一個優雅的方式,我怎麼能解決這個問題?

在此先感謝!

回答

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

也許這是對別人

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