使用with语句时,是否需要调用imap4类的close和logout方法?
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()
