Allow spawn() and friends to be used as context managers
authorThomas Kluyver <takowl@gmail.com>
Sat, 20 Dec 2014 01:05:18 +0000 (17:05 -0800)
committerThomas Kluyver <takowl@gmail.com>
Sat, 20 Dec 2014 01:05:36 +0000 (17:05 -0800)
Closes gh-111

pexpect/spawnbase.py
tests/test_misc.py

index b1bc2f36bff483bd8c5816b338d273605933592c..d79c5c0558bed8dfc60972980655033abaa6239f 100644 (file)
@@ -443,6 +443,15 @@ class SpawnBase(object):
         """Overridden in subclass using tty"""
         return False
 
+    # For 'with spawn(...) as child:'
+    def __enter__(self):
+        return self
+    
+    def __exit__(self, etype, evalue, tb):
+        # We rely on subclasses to implement close(). If they don't, it's not
+        # clear what a context manager should do.
+        self.close()
+
 class SpawnBaseUnicode(SpawnBase):
     if PY3:
         string_type = str
index 28df570e6baedf31c84f3fe948882a3c8c3cd612..792afa2f27d8c12bb8c7facb26fed69fd78e3cb0 100755 (executable)
@@ -141,6 +141,16 @@ class TestCaseMisc(PexpectTestCase.PexpectTestCase):
         with self.assertRaises(pexpect.EOF):
             child.expect('the unexpected')
 
+    def test_with(self):
+        "spawn can be used as a context manager"
+        with pexpect.spawn(sys.executable + ' echo_w_prompt.py') as p:
+            p.expect('<in >')
+            p.sendline(b'alpha')
+            p.expect(b'<out>alpha')
+            assert p.isalive()
+        
+        assert not p.isalive()
+
     def test_terminate(self):
         " test force terminate always succeeds (SIGKILL). "
         child = pexpect.spawn('cat')