Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use socket in Python as a context manager?

It seems like it would be only natural to do something like:

with socket(socket.AF_INET, socket.SOCK_DGRAM) as s: 

but Python doesn't implement a context manager for socket. Can I easily use it as a context manager, and if so, how?

like image 582
ChaimKut Avatar asked May 27 '13 11:05

ChaimKut


People also ask

How do I open a socket in Python?

It is very simple to create a socket client using the Python's socket module function. The socket. connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object.


Video Answer


1 Answers

The socket module is fairly low-level, giving you almost direct access to the C library functionality.

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: 

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: 

but the contextmanager() decorator gives you the opportunity to do other things with the socket first.

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.

like image 161
Martijn Pieters Avatar answered Sep 22 '22 14:09

Martijn Pieters