python 3.x - binary input with an ASCII text header, read from stdin -


i want read binary pnm image file stdin. file contains header encoded ascii text, , payload binary. simplified example of reading header, have created following snippet:

#! /usr/bin/env python3 import sys header = sys.stdin.readline() print("header=["+header.strip()+"]") 

i run "test.py" (from bash shell), , works fine in case:

$ printf "p5 1 1 255\n\x41" |./test.py  header=[p5 1 1 255] 

however, small change in binary payload breaks it:

$ printf "p5 1 1 255\n\x81" |./test.py  traceback (most recent call last):   file "./test.py", line 3, in <module>     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 

is there easy way make work in python 3?

to read binary data, should use binary stream e.g., using textiobase.detach() method:

#!/usr/bin/env python3 import sys  sys.stdin = sys.stdin.detach() # convert binary stream header = sys.stdin.readline().decode('ascii') # b'\n'-terminated print(header, end='') print(repr(sys.stdin.read())) 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -