1

I'd like to be able to read binary data from stdin with python.

However, when I use input = sys.stdin.buffer.read(), I get the error that AttributeError: 'file' object has no attribute 'buffer'. This seems strange because the docs say that I should be able to use the underlying buffer object - how can I fix / work around this?

Notes: I've checked out the last time this was asked, but the answers there are all either "use -u", "use buffer" (which I'm trying), or something about reading from files. The first and last don't help because I have no control over the users of this program (so I can't tell them to use particular arguments) and because this is stdin - not files.

Community
  • 1
  • 1
Everyone_Else
  • 3,206
  • 4
  • 32
  • 55
  • You are reading the documentation for Python 3, but using Python 2. – juanpa.arrivillaga Feb 25 '17 at 00:41
  • You can just use `sys.stdin.read()`. It's already a binary stream. – tavnab Feb 25 '17 at 00:46
  • This solution was mentiond in the comments of the question you linked to: `sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0)` – juanpa.arrivillaga Feb 25 '17 at 00:47
  • @tavnab sure, but that is reading in text mode, which if that's the case, doesn't the OP really just want `raw_input`? Have I just not slept enough? – juanpa.arrivillaga Feb 25 '17 at 00:53
  • @juanpa.arrivillaga you're right, it's opened in text mode by default. The `-u` would still be needed to read it in unbuffered & binary mode. If the OP's expecting to read unbuffered (i.e. no waiting for the newline) from the keyboard though (e.g. writing a game), they'll probably also need to enable "raw" mode on the tty – tavnab Feb 25 '17 at 01:07
  • @tavnab or use `os.fdopen(sys.stdin.fileno(), 'rb', 0)` buy I suspect the OP really just wants raw_input – juanpa.arrivillaga Feb 25 '17 at 01:30

1 Answers1

3

Just remove the buffer for python2:

import sys

input = sys.stdin.read()
nico
  • 2,022
  • 4
  • 23
  • 37
  • Thank you! I thought I'd have to do something special for this and I am pleasantly surprised that that was not the case. – Everyone_Else Feb 25 '17 at 00:47