PyCharm: msvcrt.kbhit() and msvcrt.getch() not wor

2020-04-02 06:08发布

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?

2条回答
不美不萌又怎样
2楼-- · 2020-04-02 06:38

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.
查看更多
\"骚年 ilove
3楼-- · 2020-04-02 06:48

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

  • Check the Emulate terminal in output console setting checkbox in Run/Debug Configurations
查看更多
登录 后发表回答