Search code examples
pythoncgetch

why does following code give different output in C , Python?


I want to implement the input taking process of $cat in Unix. Inside an infinite loop, whenever I'll press any key, the corresponding letter will be printed on the screen. If I press ctrl+d, loop will get terminated.

This TurboC code does exactly what i want:

#include<stdio.h>
#include<conio.h>

void main()
{
    char ch;
    while(1)
    {
        ch = getch();
        if(ch == 4)
            break;
        else
            printf("%c", ch);
    }
}

But whenever I'm switcihing into Python3, it's creating problem.

from msvcrt import getch

while True:
    ch = getch()
    if ord(ch) == 4: break
    else: print(ch.decode(), end="")

When the program is in infinite loop, it doesn't print anything but I'm pressing keys. Finally when I press ctrl+d, then all previously inputted characters are getting printed together.

How can I implement that in Python?


Solution

  • The problem is that the output in Python is buffered unless you flush it with sys.stdout.flush() or print(ch.decode(), end="", flush=True) as @AlbinPaul advised. You may face the same problem is C++ if you use std::cout instead of printf. The idea behind that is that each input/output operation is quite expensive, so you would observe decrease of performance if you output each character one-by-one into an output device immediately. It is much cheaper to keep the output in memory and flush this accumulated output only from time to time, so most high-level languages choose to buffer the output.

    Sometimes this buffering can bring problems if you need realtime interaction (like in your case). Another possible notorious problem is competitive programming: don't forget to flush your output, otherwise you hit the time limit.