From ac625351643d5732bcaa77844ef1506bf5c978ab Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Wed, 9 Dec 2009 00:01:27 +0000 Subject: Issue #7461: objects returned by os.popen() should support the context manager protocol --- Lib/os.py | 4 ++++ Lib/test/test_popen.py | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/Lib/os.py b/Lib/os.py index ec5d280..2a9937f 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -650,6 +650,10 @@ class _wrap_close: return returncode else: return returncode << 8 # Shift left to match old behavior + def __enter__(self): + return self + def __exit__(self, *args): + self.close() def __getattr__(self, name): return getattr(self._stream, name) def __iter__(self): diff --git a/Lib/test/test_popen.py b/Lib/test/test_popen.py index 99ad41d..24fb846 100644 --- a/Lib/test/test_popen.py +++ b/Lib/test/test_popen.py @@ -49,6 +49,14 @@ class PopenTest(unittest.TestCase): else: self.assertEqual(os.popen("exit 42").close(), 42 << 8) + def test_contextmanager(self): + with os.popen("echo hello") as f: + self.assertEqual(f.read(), "hello\n") + + def test_iterating(self): + with os.popen("echo hello") as f: + self.assertEqual(list(f), ["hello\n"]) + def test_main(): support.run_unittest(PopenTest) -- cgit v0.12