python类close()的实例源码

SocketServer.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        try:
            #explicitly shutdown.  socket.close() merely releases
            #the socket and waits for GC to perform the actual close.
            request.shutdown(socket.SHUT_WR)
        except socket.error:
            pass #some platforms may raise ENOTCONN here
        self.close_request(request)
main.py 文件源码 项目:honeypot 作者: fabio-d 项目源码 文件源码 阅读 47 收藏 0 点赞 0 评论 0
def handle_tcp_default(sk, dstport):
    # Attempt to guess protocol according to what the client sends
    data = ''
    try:
        rlist, _, _ = select.select([sk], [], [], 30)
        if len(rlist) != 0:
            data = sk.recv(20, socket.MSG_PEEK)
    except Exception as err:
        #print(traceback.format_exc())
        pass

    if data[:3] in SSL_CLIENT_HELLO_SIGNATURES:
        print colored("Guessing this is a SSL/TLS connection, attempting to handshake.", 'red', attrs=['bold'])
        handle_tcp_hexdump_ssl(sk, dstport)
    elif data.startswith("GET "):
        handle_tcp_http(sk, dstport)
    elif data.startswith("CONNECT "):
        handle_tcp_httpproxy(sk, dstport)
    else:
        handle_tcp_hexdump(sk, dstport)
    sk.close()

# UDP DISPATCHER
xiaomihub.py 文件源码 项目:aqara-mqtt 作者: monster1025 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _send_socket(self, cmd, rtnCmd, ip, port):
        socket = self._socket
        try:
            _LOGGER.debug('Sending to GW {0}'.format(cmd))
            self._read_unwanted_data()

            socket.settimeout(30.0)
            socket.sendto(cmd.encode(), (ip, port))
            socket.settimeout(30.0)
            data, addr = socket.recvfrom(1024)
            if len(data) is not None:
                resp = json.loads(data.decode())
                _LOGGER.debug('Recieved from GW {0}'.format(resp))
                if resp["cmd"] == rtnCmd:
                    return resp
                else:
                    _LOGGER.error("Response from {0} does not match return cmd".format(ip))
                    _LOGGER.error(data)
            else:
                _LOGGER.error("No response from Gateway")
        except socket.timeout:
            _LOGGER.error("Cannot connect to Gateway")
            socket.close()
authers.py 文件源码 项目:enteletaor 作者: cr0hn 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def brute_zmq(host, port=5555, user=None, password=None, db=0):

    context = zmq.Context()

    # Configure
    socket = context.socket(zmq.SUB)
    socket.setsockopt(zmq.SUBSCRIBE, b"")  # All topics
    socket.setsockopt(zmq.LINGER, 0)  # All topics
    socket.RCVTIMEO = 1000  # timeout: 1 sec

    # Connect
    socket.connect("tcp://%s:%s" % (host, port))

    # Try to receive
    try:
        socket.recv()

        return True
    except Exception:
        return False
    finally:
        socket.close()
scan_main.py 文件源码 项目:enteletaor 作者: cr0hn 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def handle_zmq(host, port=5555, extra_config=None):

    # log.debug("      * Connection to ZeroMQ: %s : %s" % (host, port))

    context = zmq.Context()

    # Configure
    socket = context.socket(zmq.SUB)
    socket.setsockopt(zmq.SUBSCRIBE, b"")  # All topics
    socket.setsockopt(zmq.LINGER, 0)  # All topics
    socket.RCVTIMEO = 1000  # timeout: 1 sec

    # Connect
    socket.connect("tcp://%s:%s" % (host, port))

    # Try to receive
    try:
        socket.recv()

        return True
    except Exception:
        return False
    finally:
        socket.close()
wsgiserver2.py 文件源码 项目:SalesforceXyTools 作者: exiahuang 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def close(self):
        """Close the socket underlying this connection."""
        self.rfile.close()

        if not self.linger:
            # Python's socket module does NOT call close on the kernel socket
            # when you call socket.close(). We do so manually here because we
            # want this server to send a FIN TCP segment immediately. Note this
            # must be called *before* calling socket.close(), because the latter
            # drops its reference to the kernel socket.
            if hasattr(self.socket, '_sock'):
                self.socket._sock.close()
            self.socket.close()
        else:
            # On the other hand, sometimes we want to hang around for a bit
            # to make sure the client has a chance to read our entire
            # response. Skipping the close() calls here delays the FIN
            # packet until the socket object is garbage-collected later.
            # Someday, perhaps, we'll do the full lingering_close that
            # Apache does, but not today.
            pass
wsgiserver2.py 文件源码 项目:SalesforceXyTools 作者: exiahuang 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def respond(self):
        """Process the current request."""
        response = self.req.server.wsgi_app(self.env, self.start_response)
        try:
            for chunk in response:
                # "The start_response callable must not actually transmit
                # the response headers. Instead, it must store them for the
                # server or gateway to transmit only after the first
                # iteration of the application return value that yields
                # a NON-EMPTY string, or upon the application's first
                # invocation of the write() callable." (PEP 333)
                if chunk:
                    if isinstance(chunk, unicodestr):
                        chunk = chunk.encode('ISO-8859-1')
                    self.write(chunk)
        finally:
            if hasattr(response, "close"):
                response.close()
wsgiserver3.py 文件源码 项目:SalesforceXyTools 作者: exiahuang 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def close(self):
        """Close the socket underlying this connection."""
        self.rfile.close()

        if not self.linger:
            # Python's socket module does NOT call close on the kernel socket
            # when you call socket.close(). We do so manually here because we
            # want this server to send a FIN TCP segment immediately. Note this
            # must be called *before* calling socket.close(), because the latter
            # drops its reference to the kernel socket.
            # Python 3 *probably* fixed this with socket._real_close; hard to tell.
##            self.socket._sock.close()
            self.socket.close()
        else:
            # On the other hand, sometimes we want to hang around for a bit
            # to make sure the client has a chance to read our entire
            # response. Skipping the close() calls here delays the FIN
            # packet until the socket object is garbage-collected later.
            # Someday, perhaps, we'll do the full lingering_close that
            # Apache does, but not today.
            pass
__init__.py 文件源码 项目:bokken 作者: thestr4ng3r 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def close(self):
        """Close the socket underlying this connection."""
        self.rfile.close()

        if not self.linger:
            # Python's socket module does NOT call close on the kernel socket
            # when you call socket.close(). We do so manually here because we
            # want this server to send a FIN TCP segment immediately. Note this
            # must be called *before* calling socket.close(), because the latter
            # drops its reference to the kernel socket.
            if hasattr(self.socket, '_sock'):
                self.socket._sock.close()
            self.socket.close()
        else:
            # On the other hand, sometimes we want to hang around for a bit
            # to make sure the client has a chance to read our entire
            # response. Skipping the close() calls here delays the FIN
            # packet until the socket object is garbage-collected later.
            # Someday, perhaps, we'll do the full lingering_close that
            # Apache does, but not today.
            pass
__init__.py 文件源码 项目:bokken 作者: thestr4ng3r 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def respond(self):
        response = self.req.server.wsgi_app(self.env, self.start_response)
        try:
            for chunk in response:
                # "The start_response callable must not actually transmit
                # the response headers. Instead, it must store them for the
                # server or gateway to transmit only after the first
                # iteration of the application return value that yields
                # a NON-EMPTY string, or upon the application's first
                # invocation of the write() callable." (PEP 333)
                if chunk:
                    if isinstance(chunk, unicode):
                        chunk = chunk.encode('ISO-8859-1')
                    self.write(chunk)
        finally:
            if hasattr(response, "close"):
                response.close()
__init__.py 文件源码 项目:download-manager 作者: thispc 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def simple_response(self, status, msg=""):
        """Write a simple response back to the client."""
        status = str(status)
        buf = ["%s %s\r\n" % (self.environ['ACTUAL_SERVER_PROTOCOL'], status),
               "Content-Length: %s\r\n" % len(msg),
               "Content-Type: text/plain\r\n"]

        if status[:3] == "413" and self.response_protocol == 'HTTP/1.1':
            # Request Entity Too Large
            self.close_connection = True
            buf.append("Connection: close\r\n")

        buf.append("\r\n")
        if msg:
            buf.append(msg)

        try:
            self.wfile.sendall("".join(buf))
        except socket.error, x:
            if x.args[0] not in socket_errors_to_ignore:
                raise
__init__.py 文件源码 项目:download-manager 作者: thispc 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def close(self):
        """Close the socket underlying this connection."""
        self.rfile.close()

        if not self.linger:
            # Python's socket module does NOT call close on the kernel socket
            # when you call socket.close(). We do so manually here because we
            # want this server to send a FIN TCP segment immediately. Note this
            # must be called *before* calling socket.close(), because the latter
            # drops its reference to the kernel socket.
            self.socket._sock.close()
            self.socket.close()
        else:
            # On the other hand, sometimes we want to hang around for a bit
            # to make sure the client has a chance to read our entire
            # response. Skipping the close() calls here delays the FIN
            # packet until the socket object is garbage-collected later.
            # Someday, perhaps, we'll do the full lingering_close that
            # Apache does, but not today.
            pass
__init__.py 文件源码 项目:download-manager 作者: thispc 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def run(self):
        try:
            self.ready = True
            while True:
                conn = self.server.requests.get()
                if conn is _SHUTDOWNREQUEST:
                    return

                self.conn = conn
                try:
                    conn.communicate()
                finally:
                    conn.close()
                    self.conn = None
        except (KeyboardInterrupt, SystemExit), exc:
            self.server.interrupt = exc
client.py 文件源码 项目:LMDocker-project 作者: xiaozhazi 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def tar_file():
#create file path.
    file_path = '/tmp/' + image_name

    if False == os.path.exists(file_path):
        print 'Error, file dir %s not exist'% file_path

    full_name = '/tmp/'+image_name+'.tar'
    tar_file = tarfile.open(full_name,'w')
    for root,dirs,files in os.walk(file_path):
        for file in files:
            fullpath = os.path.join(root,file)
            tar_file.add(fullpath,arcname = file)

    tar_file.close()


    if False == os.path.isfile(full_name):
        print 'Error, tar failed'
wsgiserver.py 文件源码 项目:wsgiserver 作者: fgallaire 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def respond(self):
        """Process the current request."""
        response = self.req.server.wsgi_app(self.env, self.start_response)
        try:
            for chunk in response:
                # "The start_response callable must not actually transmit
                # the response headers. Instead, it must store them for the
                # server or gateway to transmit only after the first
                # iteration of the application return value that yields
                # a NON-EMPTY string, or upon the application's first
                # invocation of the write() callable." (PEP 333)
                if chunk:
                    if not isinstance(chunk, binary_type):
                        raise ValueError("WSGI Applications must yield bytes")
                    self.write(chunk)
        finally:
            if hasattr(response, "close"):
                response.close()
__init__.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def respond(self):
        """Process the current request."""

        """
        From PEP 333:

            The start_response callable must not actually transmit
            the response headers. Instead, it must store them for the
            server or gateway to transmit only after the first
            iteration of the application return value that yields
            a NON-EMPTY string, or upon the application's first
            invocation of the write() callable.
        """

        response = self.req.server.wsgi_app(self.env, self.start_response)
        try:
            for chunk in filter(None, response):
                if not isinstance(chunk, six.binary_type):
                    raise ValueError('WSGI Applications must yield bytes')
                self.write(chunk)
        finally:
            if hasattr(response, 'close'):
                response.close()
wsgiserver2.py 文件源码 项目:CloudPrint 作者: William-An 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def close(self):
        """Close the socket underlying this connection."""
        self.rfile.close()

        if not self.linger:
            # Python's socket module does NOT call close on the kernel
            # socket when you call socket.close(). We do so manually here
            # because we want this server to send a FIN TCP segment
            # immediately. Note this must be called *before* calling
            # socket.close(), because the latter drops its reference to
            # the kernel socket.
            if hasattr(self.socket, '_sock'):
                self.socket._sock.close()
            self.socket.close()
        else:
            # On the other hand, sometimes we want to hang around for a bit
            # to make sure the client has a chance to read our entire
            # response. Skipping the close() calls here delays the FIN
            # packet until the socket object is garbage-collected later.
            # Someday, perhaps, we'll do the full lingering_close that
            # Apache does, but not today.
            pass
wsgiserver2.py 文件源码 项目:CloudPrint 作者: William-An 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def respond(self):
        """Process the current request."""
        response = self.req.server.wsgi_app(self.env, self.start_response)
        try:
            for chunk in response:
                # "The start_response callable must not actually transmit
                # the response headers. Instead, it must store them for the
                # server or gateway to transmit only after the first
                # iteration of the application return value that yields
                # a NON-EMPTY string, or upon the application's first
                # invocation of the write() callable." (PEP 333)
                if chunk:
                    if isinstance(chunk, unicodestr):
                        chunk = chunk.encode('ISO-8859-1')
                    self.write(chunk)
        finally:
            if hasattr(response, "close"):
                response.close()
wsgiserver3.py 文件源码 项目:CloudPrint 作者: William-An 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def close(self):
        """Close the socket underlying this connection."""
        self.rfile.close()

        if not self.linger:
            # Python's socket module does NOT call close on the kernel
            # socket when you call socket.close(). We do so manually here
            # because we want this server to send a FIN TCP segment
            # immediately. Note this must be called *before* calling
            # socket.close(), because the latter drops its reference to
            # the kernel socket.
            # Python 3 *probably* fixed this with socket._real_close;
            # hard to tell.
# self.socket._sock.close()
            self.socket.close()
        else:
            # On the other hand, sometimes we want to hang around for a bit
            # to make sure the client has a chance to read our entire
            # response. Skipping the close() calls here delays the FIN
            # packet until the socket object is garbage-collected later.
            # Someday, perhaps, we'll do the full lingering_close that
            # Apache does, but not today.
            pass
wsgiserver3.py 文件源码 项目:CloudPrint 作者: William-An 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def respond(self):
        """Process the current request."""
        response = self.req.server.wsgi_app(self.env, self.start_response)
        try:
            for chunk in response:
                # "The start_response callable must not actually transmit
                # the response headers. Instead, it must store them for the
                # server or gateway to transmit only after the first
                # iteration of the application return value that yields
                # a NON-EMPTY string, or upon the application's first
                # invocation of the write() callable." (PEP 333)
                if chunk:
                    if isinstance(chunk, unicodestr):
                        chunk = chunk.encode('ISO-8859-1')
                    self.write(chunk)
        finally:
            if hasattr(response, "close"):
                response.close()
__init__.py 文件源码 项目:py-script 作者: xiaoxiamin 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def close(self):
        """Close the socket underlying this connection."""
        self.rfile.close()

        if not self.linger:
            # Python's socket module does NOT call close on the kernel socket
            # when you call socket.close(). We do so manually here because we
            # want this server to send a FIN TCP segment immediately. Note this
            # must be called *before* calling socket.close(), because the latter
            # drops its reference to the kernel socket.
            if hasattr(self.socket, '_sock'):
                self.socket._sock.close()
            self.socket.close()
        else:
            # On the other hand, sometimes we want to hang around for a bit
            # to make sure the client has a chance to read our entire
            # response. Skipping the close() calls here delays the FIN
            # packet until the socket object is garbage-collected later.
            # Someday, perhaps, we'll do the full lingering_close that
            # Apache does, but not today.
            pass
SocketServer.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        self.close_request(request)
SocketServer.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def server_close(self):
        """Called to clean-up the server.

        May be overridden.

        """
        self.socket.close()
SocketServer.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def close_request(self, request):
        """Called to clean up an individual request."""
        request.close()
SocketServer.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def close_request(self, request):
        # No need to close anything.
        pass
SocketServer.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def finish(self):
        if not self.wfile.closed:
            self.wfile.flush()
        self.wfile.close()
        self.rfile.close()
netutil_test.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def tearDown(self):
        self.resolver.close()
        super(ThreadedResolverTest, self).tearDown()
netutil_test.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def test_same_port_allocation(self):
        if 'TRAVIS' in os.environ:
            self.skipTest("dual-stack servers often have port conflicts on travis")
        sockets = bind_sockets(None, 'localhost')
        try:
            port = sockets[0].getsockname()[1]
            self.assertTrue(all(s.getsockname()[1] == port
                                for s in sockets[1:]))
        finally:
            for sock in sockets:
                sock.close()
netutil_test.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_reuse_port(self):
        socket, port = bind_unused_port(reuse_port=True)
        try:
            sockets = bind_sockets(port, 'localhost', reuse_port=True)
            self.assertTrue(all(s.getsockname()[1] == port for s in sockets))
        finally:
            socket.close()
            for sock in sockets:
                sock.close()
netutil_test.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def tearDown(self):
        self.resolver.close()
        super(ThreadedResolverTest, self).tearDown()


问题


面经


文章

微信
公众号

扫码关注公众号