0

i am trying to call a specific method by pressing a key for example: something like this: `

import keyboard

list = ["a","b","c"]

while True:
    try:
        if key.is_pressed('i'):
            list.index("a")
        elif key.is_pressed('c'):
            list.count("a")
    except:
        print("Error!")

I tried msvcrt library and found out it was only available for windows(I am using linux ubuntu 22.04) I also tried this link and it did not work.

  • 2
    Did the script above work? That's what `keyboard` was designed for. However, how would you know whether it worked? Your script is a 100% tight CPU loop that does nothing. I think you forgot to use `print`. Note that "did not work" is not very helpful. – Tim Roberts Jul 02 '23 at 17:51

2 Answers2

0

You can try the readchar library. It has some limitations but works for a lot of simple use cases.

Cube
  • 205
  • 1
  • 7
0

You could use the well-known curses library. Short example:

import curses

stdscr = curses.initscr()   # initialize curses

curses.halfdelay(1)         # wait 1 tenth of a second for keypress
t = 0
for ch in iter(stdscr.getch, ord('q')):
    if ch != curses.ERR:    # keypress
        print("You pressed %s in period %d"%(chr(ch), t))
    t += 1

curses.endwin()             # restore terminal
Armali
  • 18,255
  • 14
  • 57
  • 171