diff options
author | Thomas Kluyver <takowl@gmail.com> | 2014-12-19 17:05:18 -0800 |
---|---|---|
committer | Thomas Kluyver <takowl@gmail.com> | 2014-12-19 17:05:36 -0800 |
commit | fbe8a38de0fd59b525ea479e19a55f4d20edf107 (patch) | |
tree | 89562ccf23b29d485c58ded605217475526bad9b | |
parent | 77357d107b1ebb38287695149d7cf1e66df4addd (diff) | |
download | pexpect-fbe8a38de0fd59b525ea479e19a55f4d20edf107.tar.gz |
Allow spawn() and friends to be used as context managers
Closes gh-111
-rw-r--r-- | pexpect/spawnbase.py | 9 | ||||
-rwxr-xr-x | tests/test_misc.py | 10 |
2 files changed, 19 insertions, 0 deletions
diff --git a/pexpect/spawnbase.py b/pexpect/spawnbase.py index b1bc2f3..d79c5c0 100644 --- a/pexpect/spawnbase.py +++ b/pexpect/spawnbase.py @@ -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 diff --git a/tests/test_misc.py b/tests/test_misc.py index 28df570..792afa2 100755 --- a/tests/test_misc.py +++ b/tests/test_misc.py @@ -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') |