簡體   English   中英

關閉python中的套接字

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM