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

标签 python python-3.x imaplib

使用with语句时,是否需要调用imap4类的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 block 之外):

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

关于python - 使用with语句和imaplib时需要调用close、logout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41787579/

相关文章:

python - 如何将标准 timedelta 字符串转换为 timedelta 对象

python - 使用 python 检查重启后 AWS 实例是否启动

python - 使用 NetworkX 在 basemap 上绘制图形

python - 将命名元组转换为字典

python - Django 表单 : setting initial value on DateField

Python numpy 数组数学显示奇怪的结果

python - 如何在 Python 3 中使用 input() 读取文件

Python GMail IMAP 不返回 UID

python - 复制后如何唯一标识 IMAP 邮件?

email - 如何识别人类发送的电子邮件?