简体   繁体   中英

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 '!!!!!!!!'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM