2013-01-20 77 views
3

具有打开一个Python程序UDP套接字关闭UDP套接字没有socket.close()

receiveSock = socket(AF_INET, SOCK_DGRAM) 
receiveSock.bind(("", portReceive)) 

它有时会发生程序失败或终止我在它运行的时候,并没有达到到

receiveSock.close() 

所以,在接下来的时间我试图运行这个程序,我得到

receiveSock.bind(("",portReceive)) 
    File "<string>", line 1, in bind 
socket.error: [Errno 98] Address already in use 

如何使用shell命令(或任何其他有用的想法)关闭此套接字?

回答

4

你有两个选择:

try: 
    # your socket operations 
finally: 
    # close your socket 

或者,为Python的新版本:

with open_the_socket() as the_socket: 
    # do stuff with the_socket 

with statement将关闭块时完成了插座,或退出程序。

+0

我想到了'finally',但是在中断关闭('crl + Z')时它并没有进入到'finally'。 – URL87

+1

'CTRL + Z'暂停UNIX/Linux中的任务;所以你不会期望套接字被关闭。 –

+0

'CTRL + C'也不会进入'finally'。 – URL87

相关问题