我希望这段代码永远不会破坏。所以我创造了一个无限循环和一个" goto"在它破裂的情况下开始。但是,它仍然没有用。
root@xxx:~# cat gmail2.py
import imaplib, re
import os
import time
import socket
socket.setdefaulttimeout(60)
def again():
conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login("xx@example.com", "xxx")
while(True):
unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
print unreadCount
if int(unreadCount) > 20:
os.system('heroku restart --app sss-xxxx-203')
#os.system('ls')
#print "Restarting server...."
time.sleep(60)
again()
1
Traceback (most recent call last):
File "gmail2.py", line 22, in <module>
again()
File "gmail2.py", line 12, in again
unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
File "/usr/lib/python2.6/imaplib.py", line 703, in status
typ, dat = self._simple_command(name, mailbox, names)
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: STATUS => socket error: EOF
答案 0 :(得分:5)
这里没有任何“goto”(或Python中的任何地方),也不会确保如果循环中断它会继续运行,原因有两个:
如果抛出异常(例如imaplib.abort
),程序将退出它所处的任何函数。只有try / except才能阻止它结束。
无论此程序如何运行,again()
只会被调用一次。调用again()
函数后,它将完成,然后在该点之后继续。它不作为一个转到 - 如果代码突破了while循环,它将不会返回again
函数。
你真正想要的是这样的:
import imaplib, re
import os
import time
import socket
socket.setdefaulttimeout(60)
while(True):
conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login("xx@example.com", "xxx")
try:
unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
print unreadCount
if int(unreadCount) > 20:
os.system('heroku restart --app sss-xxxx-203')
#os.system('ls')
#print "Restarting server...."
time.sleep(60)
except:
# an error has been thrown- try again
pass
答案 1 :(得分:1)
如果要确保代码永远不会停止运行,则必须捕获again
中引发的任何异常。阅读Python Exception handling.
由于你处于无限循环中(通常不是一个好主意),你需要确保智能处理异常,首先解决引起异常的条件。否则,你最终不会重复做任何事情。
答案 2 :(得分:1)
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
您可能想尝试一下。
答案 3 :(得分:0)
尝试交换again()
为此:
def main():
while(True):
try:
again()
except:
pass
if __name__ == "__main__":
main()