需要您的帮助,它仅适用于第一个... 这个想法是先注册100次按键,并记录按键的时间和长度。
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()
答案 0 :(得分:0)
我测试了您的代码,如果您在callb函数中声明global x
,它似乎可以正常工作:
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()