Y4RD13
Y4RD13

Reputation: 984

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()

Upvotes: 0

Views: 773

Answers (2)

Y4RD13
Y4RD13

Reputation: 984

Another possible answer using threads and ctypes library. I would recommend this If you want to keep doing things on the function on_pressed.

import threading
from pynput import keyboard
from ctypes import Structure, windll, c_uint, sizeof, byref
from time import sleep
class LASTINPUTINFO(Structure):
    _fields_ = [
        ('cbSize', c_uint),
        ('dwTime', c_uint),
    ]

def get_idle_duration():
    while True:
        lastInputInfo = LASTINPUTINFO()
        lastInputInfo.cbSize = sizeof(lastInputInfo)
        windll.user32.GetLastInputInfo(byref(lastInputInfo))
        millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
        millis = millis / 1000.0
        print(millis)
        sleep(1) 
    #return  millis

keys = []

def write_keys(keys):
   for key in keys:
        k = str(key).replace("'", "")
        print(k)

def on_press(key):
    global keys
    keys.append(key)
    write_keys(keys)
    keys = []

listener = keyboard.Listener(on_press=on_press)
last_input_info = threading.Thread(target=get_idle_duration)
listener.start()
last_input_info.start()
listener.join()
last_input_info.join()

Upvotes: 3

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

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

Upvotes: 1

Related Questions