【发布时间】:2017-01-31 01:32:17
【问题描述】:
我想要一个代表 IMAP 连接的类并将其与with 语句一起使用,如下所示:
class IMAPConnection:
def __enter__(self):
connection = imaplib.IMAP4_SSL(IMAP_HOST)
try:
connection.login(MAIL_USERNAME, MAIL_PASS)
except imaplib.IMAP4.error:
log.error('Failed to log in')
return connection
def __exit__(self, type, value, traceback):
self.close()
with IMAPConnection() as c:
rv, data = c.list()
print(rv, data)
这自然会失败,因为IMAPConnections 没有属性close。当with 语句完成时,如何存储连接并将其传递给__exit__ 函数?
【问题讨论】:
标签: python imap with-statement imaplib