[Solved] Pythonic alternative of stdin/sdtout C code [closed]


Your attempt was pretty close to correct. The problem is the + '\n'. You don’t want to write a newline after every single input character. Any newlines in the input will be read and written to the output; that’s probably what you want.

import sys
ch = sys.stdin.read(1)
while (len(ch)>0):
    sys.stdout.write(ch)
    ch = sys.stdin.read(1)

You can also loop through sys.stdin to read line by line, but if you do, Python will read input in chunks, and you won’t see any output until either you’ve filled up a chunk or entered an EOF:

import sys
for line in sys.stdin:
    sys.stdout.write(line)

We can get more prompt output by using sys.stdin.readline, which doesn’t use the same chunking mechanism:

import sys
for line in iter(sys.stdin.readline, ''):
    sys.stdout.write(line)

This code uses the uncommon 2-argument form of iter, which produces an iterator that calls the function supplied as the first argument repeatedly to produce values, stopping when the function produces the value given as the second argument.

2

solved Pythonic alternative of stdin/sdtout C code [closed]