Search code examples
pythonkeyboardpicamera

How to suppress a pressed key using the Python package keyboard


I'm trying to suppress the two pressed keys 'p' and 'q' in this script. The script is build to take pictures with RPi and RPi camera, when pressing the key 'p'. If you want to quit you press 'q'. The function keyboard.is_pressed() works totally fine, but prints me the pressed key in my terminal, where another print() should appear only. Also there is the function keyboard.is_read() where you can handle suppress=True.

Here is the used script:

from picamera2 import Picamera2, Preview
import time
import keyboard

cam = Picamera2()
cam.start_preview(Preview.QTGL)
cam.start()

savepath = '/home/pk/camera/image/'
imgname = "picture"

try:
    while 1:
        if keyboard.is_pressed("p"):
            request = cam.capture_request()
            request.save("main", savepath + imgname, format="png")
            print("Picture taken and saved")
        elif keyboard.is_pressed("q"):
            print("Closing camera...")
            break
finally:
    cam.stop_preview()
    cam.stop()
    cam.close()

Output:

pPicture taken and saved

qClosing camera...


Solution

  • You can start your print string with \r to clear the console line. Also I would recommend to use some method to execute the code only once when the key is pressed (in other case there will be spam of pictures when you press the key once). You can do for example:

    from picamera2 import Picamera2, Preview
    import time
    import keyboard
    
    cam = Picamera2()
    cam.start_preview(Preview.QTGL)
    cam.start()
    
    savepath = '/home/pk/camera/image/'
    imgname = "picture"
    
    p_pressed = False
    
    try:
        while True:
            if keyboard.is_pressed('p'):
                if p_pressed is False:
                    p_pressed = True
                    request = cam.capture_request()
                    request.save("main", savepath + imgname, format="png")
                    print("\rPicture taken and saved")
            else:
                p_pressed = False
    
            if keyboard.is_pressed('q'):
                print("\rClosing camera...")
                break
    
    finally:
        cam.stop_preview()
        cam.stop()
        cam.close()
    

    Example output:

    Picture taken and saved
    Picture taken and saved
    Picture taken and saved
    Closing camera...