简体   繁体   English

Python:检查电子邮件时代码随机崩溃

[英]Python: Code crashes randomly when checking e-mail

This code: 这段代码:

import imaplib, re
import os
import time

conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login("ddd@ddd.com", "ddd")

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 warm-beach-203')
        #os.system('ls')
        #print "Restarting server...."

    time.sleep(60)

Output: 输出:

0
1
0
0
0
0
0
4
Traceback (most recent call last):
  File "gmail.py", line 10, in <module>
    unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 704, in status
    typ, dat = self._simple_command(name, mailbox, names)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 1059, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 889, in _command_complete
    typ, data = self._get_tagged_response(tag)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 990, in _get_tagged_response
    self._get_response()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 907, in _get_response
    resp = self._get_line()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 1000, in _get_line
    line = self.readline()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/imaplib.py", line 1170, in readline
    char = self.sslobj.read(1)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ssl.py", line 136, in read
    return self._sslobj.read(len)
socket.error: [Errno 60] Operation timed out

I dont understand why it crashes randomly. 我不明白为什么它会随机崩溃。

The final error line is descriptive: the connection is timing out before the IMAP operation completes. 最后一条错误线是描述性的:IMAP操作完成之前,连接已超时。 It could be simply that Gmail is running slowly. 可能只是Gmail运行缓慢。 If that's the case, you could try extending the timeout like so: 如果是这样,您可以尝试延长超时时间,如下所示:

import socket
socket.setdefaulttimeout(15)  # In seconds

where 15 is the value you've experimentally determined works well for you. 其中15是您实验确定的值,对您来说效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM