title: Streaming binary file from ssh in python
body: <p>I've recently come across the functionality or the requests package of python (<a href="http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow" rel="nofollow noreferrer">http://docs.python-requests.org/en/latest/user/advanced/#body-content-workflow</a>) that allows to defer downloading the response body until you access the Response.content of a file, as told here :
  <a href="https://stackoverflow.com/a/16696317/8376187">https://stackoverflow.com/a/16696317/8376187</a></p>
  
  <pre><code>def download_file(url):
      local_filename = url.split('/')[-1]
      # NOTE the stream=True parameter
      r = requests.get(url, stream=True)
      with open(local_filename, 'wb') as f:
          for chunk in r.iter_content(chunk_size=1024):
              if chunk: # filter out keep-alive new chunks
                  f.write(chunk)
      return local_filename
  </code></pre>
  
  <p>I use this to stream videos and since the headers of the file is present, my video player read the video smoothly.</p>
  
  <p>I would like to do the same with an SSH/SFTP file transfer, i have tryied to use paramiko for that, but my code reads the file without getting the indexes and headers of the file making my video player fail and and is also <strong>very slow</strong>.</p>
  
  <p>The code (assuming connected paramiko SSHClient() ) :</p>
  
  <pre><code>sftp_client = client.open_sftp()
  remote_file = sftp_client.open('remotefile')
  with open('localfile', 'wb') as f:
      try:
          data = remote_file.read(1024)
          while (data):
              f.write(data)
              data = remote_file.read(1024)
      finally:
          remote_file.close()
  </code></pre>
  
  <p>Is there a way to reproduce the behavior of requests' "stream=True" option with an ssh/sftp transfer in python ?</p>
  
  <p>Thanks :)</p>