Read stdin as binary

BeMy Friend picture BeMy Friend · Aug 29, 2015 · Viewed 22.4k times · Source

I have code that opens and reads a file from binary.

with open (file, mode="rb") as myfile:
    message_string=myfile.read()
    myfile.close

I now need to do the same thing reading from stdin. But I can't figure out how to read binary.

The error says byte strings only.
Any suggestions?

Answer

icktoofay picture icktoofay · Aug 29, 2015

In Python 3, if you want to read binary data from stdin, you need to use its buffer attribute:

import sys

data = sys.stdin.buffer.read()

On Python 2, sys.stdin.read() already returns a byte string; there is no need to use buffer.