Home > Enterprise >  I want to check if ANY key is pressed, is this possible?
I want to check if ANY key is pressed, is this possible?

Time:09-23

How do I check if ANY key is pressed?

this is how I know to detect one key:

import keyboard  # using module keyboard
while True:  # making a loop
    if keyboard.is_pressed('a'):  # if key 'q' is pressed
        print('You Pressed A Key!')
        break  # finishing the loop 

How do I check if any key (not just letters) is pressed? For example, if someone presses the spacebar it works, the same for numbers and function keys, etc.

CodePudding user response:

while True:
    # Wait for the next event.
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN:
        print(event.name) # to check key name

Press any key and get the key name.

CodePudding user response:

it can be done using the msvcrt module as the following:

import msvcrt

while True:
    if msvcrt.kbhit():
        key = msvcrt.getch()
        break

or the keyboard, although i am not sure of how of a good practice this code is:

import keyboard

while True:
    try:
        print(keyboard.read_key())
        break
    except:
        pass

if this is bad practice please informe me in the coments so i can mark it as unfavored

thankyou.

CodePudding user response:

On windows, you can use:

import msvcrt as m

m.getch()

Also you can check this stack thread's answer, it works with any OS.

from __future__ import print_function
import os
import platform

if platform.system() == "Windows":
    os.system("pause")
else:
    os.system("/bin/bash -c 'read -s -n 1 -p \"Press any key to continue...\"'")
    print()

Edit: Misread the question

CodePudding user response:

Correct solution in Windows is to use msvcrt Please check thread here: How to detect key presses?

I think somehow should be possible also with builtin input() command.

Have a nice day!

  • Related