0

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

Richy
  • 380
  • 2
  • 10
  • Are you launching the program from `cmd` or from IDE? – leovp Mar 23 '17 at 09:43
  • Possible duplicate of [Python read a single character from the user](http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user) – Take_Care_ Mar 23 '17 at 09:50

2 Answers2

1

I don't blame you for wanting to use IDLE for debugging but PDB, while not as convenient, can do anything that IDLE can do and it doesn't have this problem (at least in Windows XP-W10). Under PDB both kbhit and getche work correctly. Whether debugging or not, in W10 your script's first use of getch returns junk before the user presses a key but subsequent use is clean. This isn't necessary in earlier versions of Windows but it is always a good idea to precede your real use with if kbhit() : getch() to ensure a clean buffer before asking for user input.

0

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

DineshKumar
  • 1,599
  • 2
  • 16
  • 30