【问题标题】:How to catch socket timeout in Python 3?如何在 Python 3 中捕获套接字超时?
【发布时间】:2016-01-31 06:37:09
【问题描述】:

我的部分脚本:

def testConnection(self):
    # This code doesn't work
    try:
        self.imap.login(self.user, self.password)
        return True
    except:
        return False

当我尝试使用错误设置将 imaplib 连接到邮件服务器时,脚本总是因以下错误而崩溃:

Traceback (most recent call last):
  File "./mail-notifier.py", line 198, in <module>
    mail_check()
  File "./mail-notifier.py", line 161, in mail_check
    if (SettingsExist() == True and Mail().testConnection() == True):
  File "./mail-notifier.py", line 142, in __init__
    self.imap = imaplib.IMAP4_SSL(settings.value("MailServer"), settings.value("Port"))
  File "/usr/lib64/python3.4/imaplib.py", line 1221, in __init__
    IMAP4.__init__(self, host, port)
  File "/usr/lib64/python3.4/imaplib.py", line 181, in __init__
    self.open(host, port)
  File "/usr/lib64/python3.4/imaplib.py", line 1234, in open
    IMAP4.open(self, host, port)
  File "/usr/lib64/python3.4/imaplib.py", line 257, in open
    self.sock = self._create_socket()
  File "/usr/lib64/python3.4/imaplib.py", line 1224, in _create_socket
    sock = IMAP4._create_socket(self)
  File "/usr/lib64/python3.4/imaplib.py", line 247, in _create_socket
    return socket.create_connection((self.host, self.port))
  File "/usr/lib64/python3.4/socket.py", line 512, in create_connection
    raise err
  File "/usr/lib64/python3.4/socket.py", line 503, in create_connection
    sock.connect(sa)
socket.timeout: timed out

我无法捕获超时异常并打印错误消息并继续工作。我认为“除了:”可以捕获所有发生的错误。我试图设置“except socket.timeout:”但没有成功。我做错了什么?

【问题讨论】:

  • 问题似乎是在建立连接,而不是在连接超时。
  • 如何发现这个错误?
  • 尝试在您调用的位置捕获错误:mail_check()
  • 不,它也会出错。 mail_check() 仅使用我粘贴的函数并打印结果。它本身对套接字和连接什么都不做。
  • 接下来的堆栈跟踪我们有if (SettingsExist() == True and Mail().testConnection() == True): 这里testConnection() 可能会引起问题。

标签: python sockets imaplib


【解决方案1】:

socket.connect(address)

连接到地址处的远程套接字。 (地址的格式取决于地址族——见上文。)

如果连接被信号中断,该方法将等待连接完成,或者如果信号处理程序没有引发异常并且套接字阻塞或超时,则在超时时引发socket.timeout。对于非阻塞套接字,如果连接被信号中断(或信号处理程序引发的异常),该方法会引发InterruptedError 异常。

在 3.5 版中更改:如果连接被信号中断,则该方法现在等待连接完成而不是引发 InterruptedError 异常,信号处理程序不会引发异常并且套接字阻塞或超时(请参阅 PEP 475 了解基本原理)。

在远程连接的情况下,您应该检查是否可以建立 Internet 连接(您和远程目标都可以访问)并且执行您想要的操作的连接设置是否正确。

【讨论】:

    猜你喜欢
    • 2014-07-09
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2016-02-14
    • 1970-01-01
    • 2011-12-08
    相关资源
    最近更新 更多