Search code examples
pythonmultithreadingtimepynput

How to make a timer between on press and on release functions on Pynput?


I want to make a timer that starts when no key is being pressed, and when any key is pressed, the timer is reset. I really don't know how to accomplish this, but I think it is possible using the threading and time library.

SAMPLE CODE:

import threading, time
from pynput import keyboard

keys = []

def write_keys(keys):
   for key in keys:
        k = str(key).replace("'", "")
        # do some stuff here

def on_press(key):
    # the timer will reset if a key is pressed
    global keys
    keys.append(key)
    write_keys(keys)
    keys = []

def on_release(key):
    print(f'{key} was released')
    # the timer will start when no key is pressed

# Collecting events
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

Solution

  • That's seems easy, the below code will print the seconds since the last time you pressed any keys.

    import time
    from pynput import keyboard
    
    counter_time = 0
    
    def on_press(key):
        # the timer will reset if a key is pressed
        global counter_time
        counter_time = 0
    
    # Collecting events
    listener = keyboard.Listener(on_press=on_press)
    listener.start()
    while True:
        print(f"Now the time is:{counter_time} since the last time you pressed any keys")
        time.sleep(0.5)
        counter_time += 0.5