admin管理员组

文章数量:1125626

Could you please explain me the logic of the return value of sys.stdin.read.read(10) in following code, according to the documentation? Honestly, I was not able to deduce it.

import sys, os

os.set_blocking(sys.stdin.fileno(), False)
c = sys.stdin.read(10)
print(c)

This is my top-bottom reasoning about what I should expect, which is probably flawed because it finishes in a dead end:

  1. sys.stdin is among (citation) "regular texts file like those returned by open()", so by deduction it is a TextIOWrapper object.

  2. A TextIOWrapper object is

A buffered text stream providing higher-level access to a BufferedIOBase buffered binary stream. It inherits from TextIOBase.

  1. All io.TextIO documentation does not discriminate between blocking/non-blocking. Specifically, io.TextIOBase.read(size=-1, /)

Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.

  1. BufferedIOBase documentation states that methods such as read() (bold is mine):

[...] can raise BlockingIOError if the underlying raw stream is in non-blocking mode and cannot take or give enough data;

To complicate things further, I noticed that sys.stdout.buffer exists (at least in my CPython implementation) and it is a BufferedReader, which inherits from BufferedIOBase, and

  1. the documentation states that io.BufferedReader.read(size=-1, /):

Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.

(by the way, my English is not good enough to understand what shall be returned in case of a call that blocks in non-blocking mode).

Finally:

  1. PEP3116 states that (bold is mine; today IOError has been replaced by OSError)

At the Buffered I/O and Text I/O layers, if a read or write fails due a non-blocking condition, they raise an IOError with errno set to EAGAIN.

which seems to be in contrast with 4) ("raise" vs "can raise") and 5) ("raise" vs not-raise at all).

本文标签: pythonDeducing the behavior of nonblocking sysstdinread()Stack Overflow