title: How to Communicate with a Chess engine in Python?
body: <p>On Windows 7 I can communicate with a chess engine via command line. Small Example Session with <a href="http://www.stockfishchess.com/" rel="nofollow noreferrer">Stockfish</a> on Win 7:</p>
  <pre><code>C:\run\Stockfish&gt;stockfish-x64.exe
  Stockfish 2.2.2 JA SSE42 by Tord Romstad, Marco Costalba and Joona Kiiski
  quit
  
  C:\run\Stockfish&gt;
  </code></pre>
  <p>The first line was output by the engine and the 'quit' was what I typed to quit the engine (There are <a href="http://wbec-ridderkerk.nl/html/UCIProtocol.html" rel="nofollow noreferrer">other things I can do</a>, but that's clear to me).</p>
  <p>Now I want to communicate with that engine from python:</p>
  <pre><code>import subprocess
  engine = subprocess.Popen(
      'stockfish-x64.exe',
      stdin=subprocess.PIPE,
      stdout=subprocess.PIPE,
  )
  for line in engine.stdout:
      print(line.strip())
  engine.stdin.write('quit\n')
  </code></pre>
  <p>and i get</p>
  <pre><code>C:\run\Stockfish&gt;communicate.py
  b'Stockfish 2.2.2 JA SSE42 by Tord Romstad, Marco Costalba and Joona Kiiski'
  </code></pre>
  <p>But it doesn't quit the engine (no <code>C:\run\Stockfish&gt;</code> prompt), it keeps waiting for input. I have to close the window by hand. It seems not to get my quit message (last line of the python script) written to stdin.</p>
  <p>In other words, I can read from stdout but when I write to stdin nothing happens.</p>
  <p>What am I doing wrong and how to do it right?</p>