Search code examples
pythoniostdinblocking

Blocking read from stdin in python


How to perform a blocking read operation from stdin in python (2.7) that pauses process until some data appears in the pipe?

The problem with read() lies in the fact that after the first time it returns, read() does not block anymore. Example:

echo 'test test ' | python test.py

# test.py
import sys
while True:
  string = sys.stdin.read() # Blocks only for the first time
  print '!!!!!!!!'

Solution

  • f.read() blocks, but also returns an empty string if EOF is reached. Your example is broken, since the input stream is closed and EOF is reached. Also you most likely wanted to read an entire line, so readline is appropriate.