Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm: msvcrt.kbhit() and msvcrt.getch() not working?

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?

like image 760
user4953886 Avatar asked May 29 '15 16:05

user4953886


People also ask

What is the difference between getch () and kbhit () in PyCharm?

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: I am using Windows 7, PyCharm 3.4 (the same heppens in idle).

How to use MSVCRT with PyCharm editor?

If you want to use msvcrt with the PyCharm editor, a possible workaround is to " emulate terminal in output console " available on editing the Run/Debug Configuration. This was successful for me! You could also switch to a different interface by using tkinter or pygame, both of which work with PyCharm.

Does PyCharm support RFC 4716 keys?

The RFC 4716 format for OpenSSH keys is not supported by PyCharm. Repeat the configuration step in the Add Python interpreter dialog. The Profile command is not available in the Run menu. This functionality is available only in the Professional edition of PyCharm. The Diagrams plugin that is bundled with PyCharm Professional has been disabled.

Why can’t I install a package in PyCharm?

You do not have permissions to write in the directories used by PyCharm. Check and modify your permissions. Package installation fails. pip is not available for a particular Python interpreter, or any of the installation requirements is not met.


2 Answers

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

  • Check the Emulate terminal in output console setting checkbox in Run/Debug Configurations
like image 121
ClintH Avatar answered Sep 22 '22 14:09

ClintH


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".

like image 31
Dumsboo Avatar answered Sep 23 '22 14:09

Dumsboo