1

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?

Debtanu Gupta
  • 65
  • 1
  • 6
  • flush the buffer `sys.stdout.flush()` or `print(ch.decode(), end="", flush=True)` – Albin Paul Nov 23 '19 at 15:05
  • Dear Albin Paul, Thanks a lot. It helps me too much. <3 But, if you don't mind, can you explain the working difference of C and Python at this case? – Debtanu Gupta Nov 23 '19 at 15:14
  • I don't know the entire working. But most languages are buffered to some extent. if you cannot get the output just flush the buffer. if the output goes above the buffer size or the program is terminated it will get automatically flushed or you have to manually flush the buffer to see the output in terminal. – Albin Paul Nov 23 '19 at 15:31
  • Okay okay thanks a lot again :) – Debtanu Gupta Nov 23 '19 at 15:44

1 Answers1

1

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.

Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40