如何在 Python 中使用套接字作为上下文管理器? [英] How to use socket in Python as a context manager?
问题描述
这样做似乎很自然:
with socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
但是 Python 没有为套接字实现上下文管理器.我可以轻松地将它用作上下文管理器吗?如果可以,如何使用?
but Python doesn't implement a context manager for socket. Can I easily use it as a context manager, and if so, how?
推荐答案
socket
模块相当低级,让您几乎可以直接访问 C 库功能.
The socket
module is fairly low-level, giving you almost direct access to the C library functionality.
您始终可以使用 contextlib.contextmanager代码>装饰器
来构建你自己的:
You can always use the contextlib.contextmanager
decorator to build your own:
import socket
from contextlib import contextmanager
@contextmanager
def socketcontext(*args, **kw):
s = socket.socket(*args, **kw)
try:
yield s
finally:
s.close()
with socketcontext(socket.AF_INET, socket.SOCK_DGRAM) as s:
或使用 contextlib.closure()
达到同样的效果:
or use contextlib.closing()
to achieve the same effect:
from contextlib import closing
with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s:
但是 contextmanager()
装饰器让你有机会先用套接字做其他事情.
but the contextmanager()
decorator gives you the opportunity to do other things with the socket first.
Python 3.x 确实使 socket()
成为上下文管理器,但文档没有更新以反映这一点 直到 2016 年进入 Python 3.5 周期.请参阅socket
类 在源代码中,添加了 __enter__
和 __exit__
方法.
Python 3.x does make socket()
a context manager, but the documentation wasn't updated to reflect this until well into the Python 3.5 cycle, in 2016. See the socket
class in the source code, which adds __enter__
and __exit__
methods.
这篇关于如何在 Python 中使用套接字作为上下文管理器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!