[英]Closing sockets in python
我正在修改具有以下形式的Python代码:
def foo(self):
try:
connect socket
except Exception, e:
some error reporting stuff
return an error
use the socket
do some other stuff
if some condition:
return
do some more stuff
socket.close()
return normally
来自Java我想尝试一下 - 最后围绕整个事情确保套接字关闭。 这个代码是否也应该具有这种代码,或者它是否会在背景中发生某种Pythonic魔法,使得它不需要?
我在python文档中读到,当它们被垃圾收集时,套接字被关闭了。 但依靠垃圾收集器关闭你的插座并不是那么好。
您可以使用在Python 2.5中添加的try-finally
块:
try:
open socket
do stuff with socket
finally:
close socket
或者你可以使用在Python 2.6中添加的with
语句(并且可以在2.5中使用from __future__ import with_statement
声明):
with open_the_socket() as s:
use s
这将在退出内部块时自动关闭套接字,无论它是正常退出还是通过异常退出,前提是套接字类在其__exit__()
方法中关闭。
从Python 2.7.2 __exit__()
,在socket类上没有实现__exit__()
方法。
你似乎想要添加finally块来尝试/除2.5
http://docs.python.org/whatsnew/2.5.html#pep-341-unified-try-except-finally
当收集垃圾是一种不好的做法时,依靠自动关闭是正确的,最好在完成它们后关闭它们。 尝试/终于是一个很好的方法。
不要忘记在close()之前调用shutdown()。
除了try / finally块之外,请考虑设置套接字默认超时,该超时将在指定时间后自动关闭套接字。
http://docs.python.org/library/socket.html?highlight=setdefaulttimeout#socket.setdefaulttimeout
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.