Does Python imaplib provide a given timeout?

I am looking at the imaplib Python API .

From what I can tell, there is no way to set the timeout as you can with smtplib .

It is right? How would you deal with a host that is invalid if you don't want to block it?

+6
source share
1 answer

The imaplib module imaplib not provide a way to set a timeout, but you can set a default timeout for new socket connections via socket.setdefaulttimeout :

 import socket import imaplib socket.setdefaulttimeout(10) imap = imaplib.IMAP4('test.com', 666) 

Or you can also override the imaplib.IMAP4 class with some knowledge from imaplib source and docs, which provides better control:

 import imaplib import socket class IMAP(imaplib.IMAP4): def __init__(self, host='', port=imaplib.IMAP4_PORT, timeout=None): self.timeout = timeout # no super(), it an old-style class imaplib.IMAP4.__init__(self, host, port) def open(self, host='', port=imaplib.IMAP4_PORT): self.host = host self.port = port self.sock = socket.create_connection((host, port), timeout=self.timeout) # clear timeout for socket.makefile, needs blocking mode self.sock.settimeout(None) self.file = self.sock.makefile('rb') 

Please note that after creating the connection, we must return the socket timeout back to None in order to switch to blocking mode for the subsequent socket.makefile call, as indicated in the docs method:

... The socket must be in blocking mode (it cannot have a timeout) ....

+13
source

Source: https://habr.com/ru/post/971364/


All Articles