imap_host = 'imap.gmail.com'
mail = imaplib.IMAP4_SSL(imap_host)
mail.login(user,passw)
mail.select("inbox") # connect to inbox.
while True:
try:
result, data = mail.uid('search', None, 'UNSEEN')
uid_list = data[0].split()
print len(uid_list), 'Unseen emails.'
time.sleep(60)
except KeyboardInterrupt:
print 'Quitting'
return
Traceback (most recent call last):
File "gmail_new2.py", line 12, in <module>
mail.select("inbox") # connect to inbox
File "/usr/lib/python2.6/imaplib.py", line 642, in select
typ, dat = self._simple_command(name, mailbox)
File "/usr/lib/python2.6/imaplib.py", line 1060, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python2.6/imaplib.py", line 890, in _command_complete
raise self.abort('command: %s => %s' % (name, val))
imaplib.abort: command: SELECT => socket error: EOF
代码连接到gmail并返回未读电子邮件。它工作正常,但有时会返回错误并崩溃。
如何在崩溃时纠正错误或重启代码?
答案 0 :(得分:1)
如果失败的语句是mail.select
,您可以将其包装在try/except
块中并实施重试策略。
如果问题与服务可用性有关,您可能希望尝试使用指数级增长的exponential backoff strategy来计划重试尝试。
一个简单的例子如下:
selected = False
retry_timer = 1
while not selected:
try:
mail.select('inbox')
selected = True
except imaplib.abort:
time.sleep(retry_timer)
retry_timer *= 2