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.

6
  • You are reading the documentation for Python 3, but using Python 2. Commented Feb 25, 2017 at 0:41
  • You can just use sys.stdin.read(). It's already a binary stream. Commented Feb 25, 2017 at 0:46
  • This solution was mentiond in the comments of the question you linked to: sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0) Commented Feb 25, 2017 at 0: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? Commented Feb 25, 2017 at 0: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 Commented Feb 25, 2017 at 1:07

1 Answer 1

3

Just remove the buffer for python2:

import sys

input = sys.stdin.read()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I thought I'd have to do something special for this and I am pleasantly surprised that that was not the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.