]> granicus.if.org Git - python/commitdiff
Issue #7461: objects returned by os.popen() should support the context manager protocol
authorAntoine Pitrou <solipsis@pitrou.net>
Wed, 9 Dec 2009 00:01:27 +0000 (00:01 +0000)
committerAntoine Pitrou <solipsis@pitrou.net>
Wed, 9 Dec 2009 00:01:27 +0000 (00:01 +0000)
Lib/os.py
Lib/test/test_popen.py

index ec5d280b9e7aaa4fe750cc6ff0ce257922a0ddae..2a9937f12f1ceac9b1a9e751b4f39523a2eabd59 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)