Jör*_*erg 4 python sockets try-catch
我正在修改具有以下形式的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
Run Code Online (Sandbox Code Playgroud)
来自Java我想尝试一下 - 最后围绕整个事情确保套接字关闭.这个代码是否也应该具有这种代码,或者它是否会在背景中发生某种Pythonic魔法,使得它不需要?
我在python文档中读到,当它们被垃圾收集时,套接字被关闭了.但依靠垃圾收集器关闭你的插座并不是那么好.
Ada*_*eld 12
您可以使用try-finally
在Python 2.5中添加的块:
try:
open socket
do stuff with socket
finally:
close socket
Run Code Online (Sandbox Code Playgroud)
或者您可以使用with
在Python 2.6中添加的语句(并且可以在2.5中使用from __future__ import with_statement
声明):
with open_the_socket() as s:
use s
Run Code Online (Sandbox Code Playgroud)
这将在内部块退出时自动关闭套接字,无论它是正常退出还是通过异常退出,前提是套接字类在其__exit__()
方法中关闭.
从Python 2.7.2开始,该__exit__()
方法未在套接字类上实现.