19

I've tried to read one char from the console in PyCharm (without pressing enter), but to no avail. The functions msvcrt.getch() stops the code, but does not react to key presses (even enter), and msvcrt.kbhit() always returns 0. For example this code prints nothing:

import msvcrt
while 1:
    if msvcrt.kbhit():
        print 'reading'
print 'done'

I am using Windows 7, PyCharm 3.4 (the same heppens in idle).

What is wrong? Is there any other way to just read input without enter?

colidyre
  • 4,170
  • 12
  • 37
  • 53
user4953886
  • 191
  • 1
  • 1
  • 3
  • 1
    Same problem here. There doesn't seem to be any way to capture a keypress inside the Run console. I really hope someone address this. – GrizzlyGuru Jun 26 '15 at 14:02
  • 1
    Same here, `key = msvcrt.getch()` doesn't work in PyCharm 5.0.4. – Danijel Feb 24 '16 at 14:58
  • 1
    I asked on intellij tracker to fix that. If you want it too you can upvote the issue in here: https://youtrack.jetbrains.com/issue/PY-21240 – Vit Bernatik Oct 25 '16 at 17:09
  • @VitBernatik I too seem to be having the same problem. Any work arounds to this? – Moondra May 25 '17 at 16:18

3 Answers3

18

It's possible in a special mode of the Run window.

  • Check the Emulate terminal in output console setting checkbox in Run/Debug Configurations
ClintH
  • 191
  • 1
  • 6
  • It's still not helping. even after I checked the emulate terminal checkbox, I still get always false in the kbhit in pycharm and true in the regular console (if I hit any key). – pio Jul 12 '18 at 07:26
1

You are trying to compare <Class 'Bytes'> to <Class 'string'>.

Cast the key to a string and then compare:

import msvcrt

while True:
    if msvcrt.kbhit():
        key = str(msvcrt.getch())
        if key == "b'w'":
            print(key)

To run the program in the Command Line go to: edit Configurations > Execution > enable "Emulate terminal in output console".

Dumsboo
  • 11
  • 3
0

This code will fix. So use key.lower()

while True:
    key = msvcrt.getch()
    if key == "b'w'":
        print("Pressed: W without lower()")
        #It won't work.
    if key.lower() == "b'w'":
        print("Pressed: W with lower()")
        #This one will work.
#I don't know why but key.lower() works.
ForceVII
  • 355
  • 2
  • 16