Другой возможный ответ с использованием библиотеки потоков и ctypes. Я бы рекомендовал это, если вы хотите продолжать делать что-то с функцией 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()