I'm trying to control an *interactive* ssh session from python - so not running `ssh user@host command` (which there are loads of answers for) but `ssh user@host` then writing to/reading from that ssh session from Python.

What I've tried always starts with:

```
import subprocess as sp
import sys

ssh_cmd = ["ssh", "-tt", "whoever@myhost"]
proc = sp.Popen(ssh_cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
while True:
    stdin = raw_input('enter command: ')
    proc.stdin.write(b'%s\n' % stdin)

```

the problem is how to read proc.stdout:

* `proc.stdout.readlines()` doesn't work as it never returns EOF, so it blocks
* `proc.stdout.readline()` works if there is one line of data ready, but `proc.stdout` doesn't return '' when empty so there's no way to read through it, and if there's no data it blocks
* `select` and `poll` always say that `proc.stdout` is "ready" for reading regardless of whether or not `proc.stdout.readline()` will actually work.

Any suggestions?

Edit: code here is python2.7 but solutions for python3 would be fine too.
Edit: using `proc.communicate()` isn't an option here as that waits for the process to finish, and I want to keep reading/writing to it.