Search code examples
pythonpython-3.xpynput

Issue in a code to register first 100 key pressed and length


Need you help, it works only for the first one... The idea is to register first 100 keypresses with the time and the length they are pressed.

from pynput import keyboard 
import time, os

tinit = time.time()
Resultatfichier=open('Keyregister','a')
x = 1

def callb(key): #what to do on key-release
    ti1 = str(time.time() - t)[0:8] #converting float to str, slicing the float
    ti2 = str(time.time() - tinit)[0:8] #converting float to str, slicing the float
    Resultatfichier.write("At "+ti2+" The key " + str(key) + " is pressed for "+ ti1 + " seconds\n") 
    x = x + 1
    return False #stop detecting more key-releases
def callb1(key): #what to do on key-press
    return False #stop detecting more key-presses

while x <= 100:  
    with keyboard.Listener(on_press = callb1) as listener1: #setting code for listening key-press
        listener1.join()

        t = time.time() #reading time in sec

    with keyboard.Listener(on_release = callb) as listener: #setting code for listening key-release
        listener.join()

Resultatfichier.close()

Solution

  • I tested your code, it seems to work fine if you declare global x in your callb function:

    from pynput import keyboard 
    import time, os
    
    tinit = time.time()
    Resultatfichier=open('Keyregister','a')
    x = 1
    
    def callb(key): #what to do on key-release
        global x # if not then 'x' is assigned before creation because of scope of variable
        ti1 = str(time.time() - t)[0:8] #converting float to str, slicing the float
        ti2 = str(time.time() - tinit)[0:8] #converting float to str, slicing the float
        Resultatfichier.write("At "+ti2+" The key " + str(key) + " is pressed for "+ ti1 + " seconds\n") 
        x = x + 1
        return False #stop detecting more key-releases
    def callb1(key): #what to do on key-press
        return False #stop detecting more key-presses
    
    while x <= 10:  
        with keyboard.Listener(on_press = callb1) as listener1: #setting code for listening key-press
            listener1.join()
    
            t = time.time() #reading time in sec
    
        with keyboard.Listener(on_release = callb) as listener: #setting code for listening key-release
            listener.join()
    
    Resultatfichier.close()