Commit ac625351 authored by Antoine Pitrou's avatar Antoine Pitrou

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

parent 9b14f604
......@@ -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):
......
......@@ -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)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment