Python 2.5与2.7的套接字错误处理有何不同?

4 投票
1 回答
1331 浏览
提问于 2025-04-17 07:13

下面是我正在运行的一个用Python编写的Windows服务的代码片段和错误追踪信息。在Windows XP上,使用Python 2.7时,这个服务运行得很好,但我现在的生产机器上是Windows Server 2003,运行的是Python 2.5。我遇到的主要错误是'error'对象没有'errno'这个属性。我是不是在Python 2.5上做了什么根本错误的事情,而在2.7上却能正常工作呢?

代码片段:

try:
     if s == None:
          s = self.connect()
     char = s.recv(1)
     line += char

except socket.timeout:
    if s != None:
        s.close()
    s = None
    continue

except socket.error, socket_error:
    servicemanager.LogErrorMsg(traceback.format_exc())

    if socket_error.errno == errno.ECONNREFUSED:
        if s != None:
            s.close()
        time.sleep(60)

        s =None                    
        continue

    else:
        if s != None:
            s.close()
        os._exit(-1)

else:
    pass

错误追踪片段:

if socket_error.errno == errno.ECONNREFUSED:
AttributeError: 'error' object has no attribute 'errno' 
%2: %3

1 个回答

5

在这里有解释,在 Python 2.6 版本中:

在 2.6 版本中进行了更改:socket.error 现在是 IOError 的一个子类。

而 IOError 的子类都有一个 errno 成员。

如果你想在 Python 2.6 之前获取与错误相关的 errno(假设这里描述的方法适用于引发 socket.error),你需要从异常的 args 属性中获取它:

except socket.error, socket_error:
    if socket_error.args[0] == errno.ECONNREFUSED:

撰写回答