[英]Python: Catch exception and repeat 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)
有時會失去連接並停止工作。 如何捕獲異常並在每次中斷時重新啟動代碼?
謝謝
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
使用try ...
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
嘗試這個:
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:由於您需要重新連接並再試一次,所以我將conn部分移到了try塊中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.