使用with语句和imaplib时需要调用close、logout

Necessary to call close, logout when using with statement and imaplib

使用with语句时,是否需要在imap4class上调用closelogout方法?

docs 没有提供太多上下文。

Changed in version 3.5: Support for the with statement was added.

在另一个非 with example 中,他们调用了两种方法。

这样做吗?

with imaplib.IMAP4_SSL(IMAP) as imap:
    # Do some stuff
    ...
    imap.close()
    imap.logout()

或者只是这个?

with imaplib.IMAP4_SSL(IMAP) as imap:
    # Do some stuff
    ...

IMAP4.__exit__ 呼叫 logout:

def __exit__(self, *args):  # from imaplib.py
    try:
        self.logout()
    except OSError:
        pass

所以你只需要调用close(在with块之外):

with imaplib.IMAP4_SSL(IMAP) as imap:
    # Do some stuff
    imap.close()