title: binary input with an ASCII text header, read from stdin
body: <p>I want to read a binary <a href="https://en.wikipedia.org/wiki/Netpbm_format" rel="nofollow">PNM</a> image file from stdin.  The file contains a header which is encoded as ASCII text, and a payload which is binary.  As a simplified example of reading the header, I have created the following snippet:</p>
  
  <pre><code>#! /usr/bin/env python3
  import sys
  header = sys.stdin.readline()
  print("header=["+header.strip()+"]")
  </code></pre>
  
  <p>I run it as "test.py" (from a Bash shell), and it works fine in this case:</p>
  
  <pre><code>$ printf "P5 1 1 255\n\x41" |./test.py 
  header=[P5 1 1 255]
  </code></pre>
  
  <p>However, a small change in the binary payload breaks it:</p>
  
  <pre><code>$ printf "P5 1 1 255\n\x81" |./test.py 
  Traceback (most recent call last):
    File "./test.py", line 3, in &lt;module&gt;
      header = sys.stdin.readline()
    File "/usr/lib/python3.4/codecs.py", line 313, in decode
      (result, consumed) = self._buffer_decode(data, self.errors, final)
  UnicodeDecodeError: 'utf-8' codec can't decode byte 0x81 in position 11: invalid start byte
  </code></pre>
  
  <p>Is there an easy way to make this work in Python 3?</p>