问题描述
我有一个程序可以使用 IMAP IDLE 检查收件箱中的新电子邮件。每当我运行它时,它一开始都能完美运行。但一段时间后,它停止暂停空闲超时时间,而是快速循环第一部分。
from imapclient import IMAPClient
from imap_tools import MailBox,AND
while True:
try:
#this is the part that's getting looped every half second when it breaks
telegram('try portion starting again')
# Wait for up to 540 seconds for an IDLE response
responses = server.idle_check(timeout=540)
if responses:
telegram('Email Recieved')
for response in responses:
if response[0] not in checked_uids:
checked_uids.append(response[0])
uid = str(response[0])
with MailBox(HOST).login(USERNAME,PASSWORD) as mailBox:
for msg in mailBox.fetch(AND(uid=uid)):
body_text=msg.text
telegram(body_text)
telegram() 向我发送电报消息的地方。
因此,当它正常工作时,我会收到一条包含新电子邮件正文的消息,并且每 540 秒我就会收到一条消息,提示 try: 部分已重新开始。
在我的测试中,它像这样工作了一段时间,然后突然之间,不知为何我无法辨别,我每秒收到两次重复到无穷大的“尝试部分重新开始”消息。意思是,似乎 responses = server.idle_check(timeout=540)
部分停止按预期工作
编辑:这是我正在使用的代码的 catch 部分。超级简单。我也没有收到任何错误消息,而程序正在变得疯狂并且如此快速地循环
except KeyboardInterrupt:
break
except Exception as e:
print(e)
telegram(e)
解决方法
我想出了一个解决方案。我仍然不知道为什么会发生这种情况,但这为我解决了。
我将 server.idle()
放在 try:
代码中。然后我将 server.idle_done()
放在 finally
代码段中。这样,每次程序循环时它开始空闲,每次结束时它停止空闲。似乎每次都这样做会使程序更加稳定。