[英]Try/Except not catching UnboundLocalError on KeyboardInterrupt
I have a simple file transfer server that uses socket, It has an infinite listening to clients loop in the Main() func, so i surrounded it with Try/Except with KeyboardInterrupt so i would be able to properly close all the sockets and connections when CTRL+C-ing out 我有一个使用套接字的简单文件传输服务器,它在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()
Now when a client connects and does whatever and i close it via keyboard interrupt it works fine, printing me the 'Manual Close' 现在,当客户端连接并执行任何操作时,我通过键盘中断将其关闭,可以正常工作,并向我显示“手动关闭”
But when i close via keyboardinterrupt before a client connects it gives me this error: UnboundLocalError: local variable 'conn' referenced before assignment
但是,当我在客户端连接之前通过keyboardinterrupt关闭时,会出现以下错误: UnboundLocalError: local variable 'conn' referenced before assignment
I understand the conn
doesn't get assigned if a client doesn't connect but i thought that any errors under except
get ignored 我了解如果客户端未连接,则不会分配conn
,但我认为except
下的任何错误都会被忽略
You can just put the functions within the except block inside another try/except
and tell it to ignore the exception with pass 您可以将函数放在另一个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.