尝试/不在KeyboardInterrupt上捕获UnboundLocalError

时间:2017-10-20 10:03:14

标签: python sockets

我有一个使用套接字的简单文件传输服务器,它在Main()函数中有无限的监听客户端循环,所以我用KeyboardInterrupt的Try / Except包围它,这样我就能正确关闭所有的套接字CTRL + C-ing出来时的连接和连接

def Main():
    try:
        #various variable initations
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.bind((host,port))
        print 'Socket bound to host - {0} and port {1}'.format(host,port)

        sock.listen(5)

        print 'Waiting for connections...'

        while True:
            conn, addr = sock.accept()
            print 'Client IP:',str(addr)
            #getting data from client and making the server do the appropriate functions

        conn.close()        
        sock.close()
    except(KeyboardInterrupt): # redundancy to make sure that a keyboard interrupt to close the program also closes the sockets and connections
        conn.close()
        sock.close()
        print 'Manual Close'
        sys.exit()

现在,当客户端连接并执行任何操作并通过键盘中断将其关闭时,它工作正常,打印出“手动关闭”

但是当我在客户端连接之前通过keyboardinterrupt关闭它时会出现这个错误:UnboundLocalError: local variable 'conn' referenced before assignment

我理解如果客户端没有连接,conn没有被分配,但我认为except下的任何错误都会被忽略

1 个答案:

答案 0 :(得分:0)

您可以将except块中的函数放在另一个try/except内,并告诉它忽略带有传递的异常

except(KeyboardInterrupt): # redundancy to make sure that a keyboard interrupt to close the program also closes the sockets and connections
    try:
        conn.close()
        sock.close()
    except:
        pass
    print 'Manual Close'
    sys.exit()