我希望这段代码永远不会破坏.所以我创建了一个无限循环和一个"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
Run Code Online (Sandbox Code Playgroud)
这里没有任何"goto"(或Python中的任何地方),也不会确保如果循环中断它会继续运行,原因有两个:
如果一个异常(例如imaplib.abort抛出,程序将退出它所处的任何函数.只有try/except会阻止它结束.
无论这个程序如何运行,again()都只会被调用一次.again()调用该函数后,它将完成,然后在该点之后继续.它并没有,如果代码爆发,虽然循环充当goto-,它不会返回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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1712 次 |
| 最近记录: |