title: How to control an interactive ssh session with Python's subprocess
body: <p>I'm trying to control an <em>interactive</em> ssh session from python - so not running <code>ssh user@host command</code> (which there are loads of answers for) but <code>ssh user@host</code> then writing to/reading from that ssh session from Python.</p>
  
  <p>What I've tried always starts with:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>the problem is how to read proc.stdout:</p>
  
  <ul>
  <li><code>proc.stdout.readlines()</code> doesn't work as it never returns EOF, so it blocks</li>
  <li><code>proc.stdout.readline()</code> works if there is one line of data ready, but <code>proc.stdout</code> doesn't return '' when empty so there's no way to read through it, and if there's no data it blocks</li>
  <li><code>select</code> and <code>poll</code> always say that <code>proc.stdout</code> is "ready" for reading regardless of whether or not <code>proc.stdout.readline()</code> will actually work.</li>
  </ul>
  
  <p>Any suggestions?</p>
  
  <p>Edit: code here is python2.7 but solutions for python3 would be fine too.
  Edit: using <code>proc.communicate()</code> isn't an option here as that waits for the process to finish, and I want to keep reading/writing to it.</p>