除了KeyboardInterrupt之外,如何正常关闭带有sock.close()的套接字:在类之外

时间:2015-08-14 22:01:08

标签: python sockets

鉴于此部分代码,当按Ctrl + C时,程序返回错误“name'sock'未定义。”。我想这是正常的,因为sock.close()在课堂之外,但我应该怎么做才能阻止它?

在我的情况下,它是关于一个客户端,而不是服务器,要求关闭套接字。

import socket

class something(object):
    def connect(self):
        self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((self.tcp_ip, self.tcp_port))
        # etc.

if __name__ == '__main__':
    try:
        app = something()
        app.connect()
    except KeyboardInterrupt:
        pass
    finally:
        sock.close()

2 个答案:

答案 0 :(得分:2)

我觉得这应该有用

import socket
class something(object):
    def __init__(self):
        self.sock = None

    def connect(self):
        self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect(('127.0.0.1', 12397))
        self.sock.recv(1024)

    def close(self):
        self.sock.close()

if __name__ == '__main__':
    try:
        sk = something()
        sk.connect()
    except KeyboardInterrupt:
        pass
    finally:
        sk.close()
        print "Socket Closed"

答案 1 :(得分:-1)

试试这个。

if __name__ == '__main__':
    try:
        foo = something()
        foo.connect()
    except KeyboardInterrupt:
        pass
    finally:
        foo.sock.close()