[英]Try/Except not catching UnboundLocalError on KeyboardInterrupt
我有一个使用套接字的简单文件传输服务器,它在Main()函数中具有无限监听客户端循环的功能,因此我将其与Try / Except一起使用KeyboardInterrupt进行了包围,这样,当我可以正确关闭所有套接字和连接时, CTRL + C退出
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
下的任何错误都会被忽略
您可以将函数放在另一个try/except
的except块中,并告诉它通过pass忽略异常
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.