Python:捕获异常并重复代码

时间:2011-06-21 19:22:59

标签: python

我有这段代码:

import imaplib, re
import os
import time

conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login("ddd", "dddd")

while(True):
        unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
        print unreadCount

        if int(unreadCount) > 10:
                print "restarting..."

        time.sleep(50)

有时会丢失连接并停止工作。如何捕获异常并在每次中断时启动代码?

由于

3 个答案:

答案 0 :(得分:3)

import imaplib, re
import os
import time

while True:
    try:
        conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
        conn.login("ddd", "dddd")

        while True :
                unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
                print unreadCount

                if int(unreadCount) > 10:
                        print "restarting..."

                time.sleep(50)
    except HypotheticalException:
        pass

答案 1 :(得分:0)

使用try ... except

try:
   unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
   if int(unreadCount) > 10:
            print "restarting..."

    time.sleep(50)
except Exception:
  pass

答案 2 :(得分:0)

试试这个:

import imaplib, re
import os
import time


for n in range(3):
try:
    conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    conn.login("ddd", "dddd")
    while(True):
        unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
        print unreadCount

        if int(unreadCount) > 10:
            print "restarting..."

        time.sleep(50)
    break
except Exception, e:
    if n == 2:
        print >>sys.stderr, "Failure During processing, restarting..."
        print >>sys.stderr, e

您可以将n设置为您想要允许的尝试次数。

修改 嗯,经过进一步细读,似乎我的代码略有错误。我编辑并修复了我的版本。你需要调整和编辑你的while循环,因为我不完全确定你在做什么。

编辑2: 由于您需要重新连接并重试,我已经在try块中移动了conn部分。