3

I have the following code (in its own file/ script/ program):

from msvcrt import getch

while True:
    key = ord(getch())
    print('You pressed', key)

and I have ran it in PyCharm's console and pressed all sorts of keys, alpha's, numbers, and arrow keys but there is no output at all.

Is there something wrong, or do you need me to provide more information?

Thanks!

2 Answers2

1

This doesn't work for me either, nor does martineau's suggested code even after fixing the TypeError (in an edit he rejected, by the way). As far as I can tell, the PyCharm console is consuming the input before the program has a chance to read it.

In looking for other solutions to read input without blocking, I'm convinced it's an issue with PyCharm. For instance, asciimatics is known to not work in the console window either:

http://asciimatics.readthedocs.io/en/stable/troubleshooting.html#i-can-t-run-it-inside-pycharm-or-other-ides

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. These open a new window, however.

Hoping someone more knowledgeable of PyCharm will comment on this, and maybe even bug it in that project. Especially across platforms, non-blocking text input is so simple yet so annoying! Grrr!

-1

Sounds like it might be an issue with PyCharm's console.

For the OS command-line console (cmd.exe) callinggetch()isn't always quite that simple. Here's something I've used in my own code. Also note the link in the comment.

# see http://msdn.microsoft.com/en-us/library/078sfkak
import msvcrt

def readch(echo=True):
    "Get a single character on Windows."
    while msvcrt.kbhit():  # clear out keyboard buffer
        ch = msvcrt.getch()
        if ch in '\x00\xe0':  # arrow or function key prefix?
            ch = msvcrt.getch()  # second call returns the actual key code
    ch = msvcrt.getch()
    if ch in '\x00\xe0':  # arrow or function key prefix?
        ch = msvcrt.getch()  # second call returns the actual key code
    if echo:
        msvcrt.putch(ch)
    return ch

Note: You may not need the initialwhileloop, depending on what you're doing.

martineau
  • 119,623
  • 25
  • 170
  • 301