diff -r 3128f51967b4 Doc/library/telnetlib.rst --- a/Doc/library/telnetlib.rst Fri Nov 20 13:19:35 2015 -0800 +++ b/Doc/library/telnetlib.rst Sat Nov 21 01:05:55 2015 +0100 @@ -43,6 +43,17 @@ :exc:`EOFError` when the end of the connection is read, because they can return an empty string for other reasons. See the individual descriptions below. + :class:`Telnet` class support the :keyword:`with` statement. Here is a sample + on how using it: + + >>> from telnetlib import Telnet + >>> with Telnet('localhost', 23) as tn: + ... tn.interact() + ... + + .. versionadded:: 3.6 + Support for the :keyword:`with` statement was added. + .. seealso:: diff -r 3128f51967b4 Lib/telnetlib.py --- a/Lib/telnetlib.py Fri Nov 20 13:19:35 2015 -0800 +++ b/Lib/telnetlib.py Sat Nov 21 01:05:55 2015 +0100 @@ -637,6 +637,12 @@ raise EOFError return (-1, None, text) + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + def test(): """Test program for telnetlib. @@ -660,11 +666,10 @@ port = int(portstr) except ValueError: port = socket.getservbyname(portstr, 'tcp') - tn = Telnet() - tn.set_debuglevel(debuglevel) - tn.open(host, port, timeout=0.5) - tn.interact() - tn.close() + with Telnet() as tn: + tn.set_debuglevel(debuglevel) + tn.open(host, port, timeout=0.5) + tn.interact() if __name__ == '__main__': test() diff -r 3128f51967b4 Lib/test/test_telnetlib.py --- a/Lib/test/test_telnetlib.py Fri Nov 20 13:19:35 2015 -0800 +++ b/Lib/test/test_telnetlib.py Sat Nov 21 01:05:55 2015 +0100 @@ -42,6 +42,11 @@ telnet = telnetlib.Telnet(HOST, self.port) telnet.sock.close() + def testContextManager(self): + with telnetlib.Telnet(HOST, self.port) as tn: + self.assertIsNotNone(tn.get_socket()) + self.assertIsNone(tn.get_socket()) + def testTimeoutDefault(self): self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) diff -r 3128f51967b4 Misc/NEWS --- a/Misc/NEWS Fri Nov 20 13:19:35 2015 -0800 +++ b/Misc/NEWS Sat Nov 21 01:05:55 2015 +0100 @@ -10,6 +10,9 @@ Core and Builtins ----------------- +- Issue #25485: Add the support of the `with` statement for the telnetlib.Telnet + class. Will automatically close the socket. + - Issue #25630: Fix a possible segfault during argument parsing in functions that accept filesystem paths.