[英]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 谢谢
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
Use try ... except 使用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
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. 您可以将n设置为要允许的尝试次数。
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.
您将需要调整和编辑while循环,因为我不太确定自己在做什么。
EDIT 2: Since you need to reconnect and try again, I've moved the conn section within the try block. 编辑2:由于您需要重新连接并再试一次,所以我将conn部分移到了try块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.