Search code examples
pythonpython-2.7getch

getch() in Python displaying wrong output


I tried running this code in python

from msvcrt import getch

while True:
      char = getch()
      print char

but this is displaying the character 'ÿ' infinitely.

Can anyone help me with this Thanks in advance


Solution

  • It just works fine when I run the same program via command line. I believe you are trying in an IDE? If you are using pycharm, the same query has been posted to them and it is unanswered for like a year.

    Link : Using getch() in pycharm

    Pls try the same code in command prompt and let us know.

    Updated answer :

    getch() requires a working "console" window, and when you run Idle you don't get one as its set to use pythonw.exe. Thus, it's technically not able to process any keystrokes and returns immediately. You could try to verify that by starting Idle from the command line with the standard python. (But you may have to be in that console window to trigger the getch() to return)

    I personally verified your program by launching IDLE from command line. Well it does not return that character indefinitely atleast. It doesnt return anything for that matter.

    Just out of curiosity , do you really need to use IDLE for this program? Wouldn't the regular command line suffice? If yes, am sorry I couldnt be of much help for this question.

    To launch idle from command prompt : python C:\Python27\Lib\idlelib\idle.py

    Source for the answer : IDLE does not return getch() characters