donald
donald

Reputation: 23737

Python: Catch exception and repeat code

I have this code:

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)

Which sometimes loses the connection and stops working. How can I catch the exception and start the code over every time it breaks?

Thanks

Upvotes: 0

Views: 1722

Answers (3)

Spencer Rathbun
Spencer Rathbun

Reputation: 14900

Try this:

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

You can set n to be however many tries you want to allow.

EDIT: Hmm, after further perusal, it seems I got your code slightly wrong. I've edited and fixed my version. You will need to adjust and edit your while loop, as I am not entirely sure what it is you are up to.

EDIT 2: Since you need to reconnect and try again, I've moved the conn section within the try block.

Upvotes: 0

dave
dave

Reputation: 12806

Use 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

Upvotes: 0

mystery
mystery

Reputation: 19513

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

Upvotes: 4

Related Questions