Merged revisions 76723 via svnmerge from
authorAntoine Pitrou <solipsis@pitrou.net>
Wed, 9 Dec 2009 00:03:16 +0000 (00:03 +0000)
committerAntoine Pitrou <solipsis@pitrou.net>
Wed, 9 Dec 2009 00:03:16 +0000 (00:03 +0000)
svn+ssh://pythondev@svn.python.org/python/branches/py3k

........
  r76723 | antoine.pitrou | 2009-12-09 01:01:27 +0100 (mer., 09 déc. 2009) | 3 lines

  Issue #7461: objects returned by os.popen() should support the context manager protocol
........

Lib/os.py
Lib/test/test_popen.py

index a59c5df1f6c87db707e092fc43b6520e9a1aa33d..7c342feb432641a652a73c0daa89f6f902e8c617 100644 (file)
--- 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):
index 99ad41df749ba76f185552ebf95ab479351041cd..24fb846bef105109dd22700f833cf7c07bc634ca 100644 (file)
@@ -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)