py socket:NoneType object has no attribute close

在我们使用python的socket模块调用socket.close()时,有时候会遇到这种问题:

'NoneType' object has no attribute 'close'
产生这个问题的原因是socket本身不是线程安全的( http://stackoverflow.com/questions/11177018/python-socket-and-threads),但是它对于下面是它的源码:
def close(self):
        try: 
            if self._sock:
                self.flush()
        finally:
            if self._close:
                self._sock.close()
            self._sock = None
会有可能在调用self._sock.close()前一步时,self._close被清零,例如:另一个线程将此值设为了None,处理这种问题的方法一般是:

在外面套一层try  except或者直接在socket模块外面套一层try except:

import socket
def hack_fileobject_close():
    if getattr(socket._fileobject.close, '__hacked__', None):
        return
    old_close = socket._fileobject.close
    def new_close(self, *p, **kw):
        try:
            return old_close(self, *p, **kw)
        except Exception, e:
            print("Ignore %s." % str(e))                                                                                                                                        
    new_close.__hacked__ = True
    socket._fileobject.close = new_close
hack_fileobject_close()

你可能感兴趣的:(socket,python,close)