52

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?

BeMy Friend
  • 751
  • 1
  • 6
  • 11

1 Answers1

82

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.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • 4
    Not true about Python 2. It reads in text mode by default. E.g. on Windows a file like "a\r\nb" fed into stdin will appear as "a\nb". See here for solutions: http://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin – Evgeni Sergeev Jun 28 '16 at 14:42
  • 5
    See https://stackoverflow.com/a/38939320/239247 for proper solution on Windows. – anatoly techtonik Aug 14 '16 at 05:07
  • @EvgeniSergeev Did you actually try it? `$ printf "a\r\nb\rc\r" | python2.7 -c 'import sys; print(sys.stdin.readlines())'` produces `['a\r\n', 'b\rc\r']` – Clément Dec 03 '16 at 16:02
  • 2
    @Clément: They said "on Windows". `$` suggests you aren't running it on Windows. (Unless you're using the Windows Subsystem for Linux thing, which for these purposes we can consider to be not-Windows.) – icktoofay Dec 16 '16 at 06:25