因为我发现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)
[...]
我只是复制了原来的lib并修改了它,这很有效,但我不认为这是应该做的事情。
有人能给我一个优雅的方法来解决这个问题吗?
提前谢谢!
最佳答案
好吧,所以我想我做到了。这是一个尝试和错误,而不是纯粹的知识,但它的工作。
以下是我所做的:
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()
也许这对其他人有帮助
关于python - 覆盖imaplib中的open(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16892737/