How do you read from stdin in python from a pipe which has no ending How do you read from stdin in python from a pipe which has no ending python python

How do you read from stdin in python from a pipe which has no ending


Try the next:

import sysimport timek = 0try:    buff = ''    while True:        buff += sys.stdin.read(1)        if buff.endswith('\n'):            print buff[:-1]            buff = ''            k = k + 1except KeyboardInterrupt:   sys.stdout.flush()   passprint k


For this to work without waiting until the stdin stream ends, you can iter on the readline. I think this is the simplest solution.

import sysk = 0try:   for line in iter(sys.stdin.readline, b''):      k = k + 1      print lineexcept KeyboardInterrupt:   sys.stdout.flush()   passprint k


k = 0try:    while True:        print sys.stdin.readline()        k += 1except KeyboardInterrupt:    sys.stdout.flush()    passprint k