0

I want to use the msvcrt module in python, but I can't make it work.
I am on windows 10, have several "active keyboards" (I can change it from azerty to qwerty and stuff) and did not do/download anything except Python3 itself (I'm saying that because maybe there are some requirements or manipulations to do that I don't know about).

What I'd like to do is simple -- press a key, and then do something according to the key that was pressed (so I need my computer to identify that key).

I tried it using the following code:

import msvcrt
while 1:                      #is that necessary?
    char = msvcrt.getch()
    if char == ???            #that's what I'm struggling with
        print("yay")
    else:
        print("nope") 

I simply don't know how to "call" my key. I've tried for example '\r', char(13), ASCII codes and so on, but none of these worked. Chances are, they're supposed to but I'm doing it wrong- by not working I mean, I could never get a "yay", though the "right" key was pressed.

Thanks in advance!

Megabeets
  • 1,378
  • 11
  • 19
  • Possible duplicate of [Python method for reading keypress?](https://stackoverflow.com/questions/12175964/python-method-for-reading-keypress) – Chris Aug 16 '17 at 12:06
  • Of course one way to experiment is to print out the values that `getch()` returns when you press a specific key. – holdenweb Aug 16 '17 at 12:08

2 Answers2

0

You should prepend b before the wished key, i.e:

char = char = msvcrt.getch()
if char == b"\r":
    print("yay")
else:
    print("nope")

The Python 3.3 documentation states:

Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

You can easily check it by yourself by looking at the output of msvcrt.getch() after you press the wished key.

>>> msvcrt.getch() # I pressed Enter
b'\r'
>>> msvcrt.getch() # I pressed SPACE
b' '
>>> msvcrt.getch() # I pressed BACKSPACE
b'\x08'
Megabeets
  • 1,378
  • 11
  • 19
0

This should work with Python 3 on Windows 10:

import msvcrt
import os

os.system('cls')
while True:
    print('Press key [combination] (Kill console to quit): ', end='', flush=True)
    key = msvcrt.getwch()
    num = ord(key)
    if num in (0, 224):
        ext = msvcrt.getwch()
        print(f'prefix: {num}   -   key: {ext!r}   -   unicode: {ord(ext)}')
    else:
        print(f'key: {key!r}   -   unicode: {ord(key)}')
  • For me it issued this error: ` print(f'prefix: {num} - key: {ext!r} - unicode: {ord(ext)}') ^ SyntaxError: invalid syntax` – Alon Samuel Feb 13 '19 at 17:27