2

Once I press "q" it prints this text many times. I want to print it once.

import keyboard

while True:
    try:
        if keyboard.is_pressed("q"):
            print('q pressed')
    except:
        break
  • With your script you have to keep q key pressed right ? You want to press q key single time and then print?. If so you can check python threading https://docs.python.org/3/library/threading.html#event-objects – Lanre Aug 04 '22 at 15:04
  • is_pressed will be triggered until and unless the key is released, its better you use `released` – Himanshu Poddar Aug 04 '22 at 15:04
  • Threading is also good idea, thanks :) – Piotr Rzepka Aug 04 '22 at 15:20

3 Answers3

1

Your current code is constantly repeating check until q is pressed, which is not cpu efficient, and also once the q is pressed is_pressed will always be True - it does not automatically reset.

There is a good example of what you want in the docs. Do something like this:

keyboard.wait('q')
print('q pressed, continue...')

Note that this will block execution until q is pressed, and will continue after that. If you want to repeat process, simply put it inside while loop:

while True
    keyboard.wait('q')
    print('q pressed, waiting on it again...')
nenadp
  • 798
  • 1
  • 7
  • 15
0

Hi you need to break in your try clause after printing in order for loop to end, just like you did in except;

while True:
    try:
        if keyboard.is_pressed("q"):
            print('q pressed')
            break
    except:
        break
Lanre
  • 340
  • 2
  • 6
0

The reason your code repeats is that you do not check for when q is released. this causes the condition if keyboard.is_pressed("q") to run multiple times

to stop this. you need to check for when q is released

for example

import keyboard

is_pressed = False

while True:
    try:
        if keyboard.is_pressed("q") && not is_pressed:
            print('q pressed')
            is_pressed = True:
        if not keyboard.is_pressed("q"):
            is_pressed = False

    except:
        break