如何在 Python 中使用套接字作为上下文管理器?

编程入门 行业动态 更新时间:2024-10-24 05:20:32
本文介绍了如何在 Python 中使用套接字作为上下文管理器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这样做似乎很自然:

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 中使用套接字作为上下文管理器?

本文发布于:2023-11-23 10:09:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621060.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   管理器   如何在   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!