Restrict/block key presses for input in Python and prevent keyboard key press appearing on next prompt

Viewed 2254

I'm looking for a way to restrict/block key presses for during input, except for allowing certain key(s). Also, I don't want restricted/blocked key presses to be registered on screen.

Basic example:

input("Enter the letter [p] to proceed: ")

When prompted, any key that is not the letter "p", will not appear on screen next to the input().

NOTE: I know about using a while loop to check if the correct key was pressed, but that's not what I want to use.

As a workaround, I am using print() and Keyboard python module.

Here is my basic code:

import msvcrt
import keyboard

print("Press [p] to proceed: ", end="", flush=True)

while True:
    keyboard.wait("p")
    while msvcrt.kbhit():
        msvcrt.getch()    
    print("p")      # print the letter "p" next to the previous print statement above
    break

This works for my needs, but with one annoying issue. The letter "p" is then flushed to the console, appearing on the next line at the prompt:

Any help would be appreciated.

OS: Windows 10
Python version: 3.8.3
Using Windows Terminal (version 1.0.1811.0 as of this post)
PowerShell version: 7.0.3

1 Answers

Use keyboard.block_key(key).

From the doc:

keyboard.block_key(key)
Suppresses all key events of the given key, regardless of modifiers.

Related