Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read stdin as binary [duplicate]

Tags:

python

stdin

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?

like image 477
BeMy Friend Avatar asked Aug 29 '15 03:08

BeMy Friend


1 Answers

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.

like image 190
icktoofay Avatar answered Nov 02 '22 23:11

icktoofay