Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anway to get a specific keyboard input in python

I'm working on a project for school and it currently has the line input("press enter to continue") which works but it doesn't matter what the input is as as long as the user hits enter to program continues, and i'd like it to only work when that specific key is pressed.

I looked it up and there used to be a keyboard module but for some inexplicable reason it's been removed, so is there any other way of getting an input?

like image 328
James Logie Avatar asked Nov 18 '25 17:11

James Logie


1 Answers

You can use readchar library for this purposes. It works for both Linux and Windows and should also work for MacOS but not fully tested (according to the official documentation)

pip install readchar

Here is an example of reaction to the different key-press cases:

from readchar import readkey, key

while True:
  k = readkey()
  if k == "a":
    # do stuff
  if k == key.DOWN:
    # do stuff
  if k == key.ENTER:
    break
like image 146
poisoned_monkey Avatar answered Nov 20 '25 06:11

poisoned_monkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!