Python:程序始终运行
我希望这段代码永远不会出错。所以我创建了一个无限循环,并且设置了一个“跳转”到开头的机制,以防它出错。不过,它还是没有正常工作。
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
4 个回答
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
你可以试试这个。
1
如果你想确保代码一直在运行,就必须处理在again
中出现的任何错误。可以看看Python的异常处理相关内容。
因为你在一个无限循环中(一般来说,这不是个好主意),你需要确保聪明地处理这些错误,解决导致错误发生的原因。否则,你只会不断地重复做无用的事情。
5
这里没有“goto”这个东西(在Python里也没有),而且即使循环中断了,也不会继续运行,原因有两个:
如果抛出一个异常(比如
imaplib.abort
),程序会退出当前所在的函数。只有用try/except才能阻止程序结束。不管这个程序怎么运行,
again()
函数只会被调用一次。一旦调用了again()
,它会执行完毕,然后继续往下走。它并不是像goto那样的功能——如果代码跳出了那个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