因为我发现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)
[...]我只是复制了原始库并对其进行了修改,这很有效,但我不认为这是应该这样做的方式。
有没有人能告诉我一个优雅的方法来解决这个问题?
提前感谢!
发布于 2013-06-04 14:35:00
好吧,我想我成功了。与其说是纯粹的知识,不如说是一次尝试和错误,但它是有效的。
下面是我所做的:
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-11-12 22:26:19
虽然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 headerhttps://stackoverflow.com/questions/16892737
复制相似问题