python - 在代码中发布以注册前 100 个按键和长度
问题描述
需要你的帮助,它只适用于第一个......这个想法是注册前 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()
解决方案
global x
我测试了你的代码,如果你在你的 callb 函数中声明它似乎工作正常:
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()
推荐阅读
- deployment - 主应用程序和模块版本之间的依赖关系管理
- snowflake-cloud-data-platform - 以最低权限创建雪花角色
- python - Pandas:在同一 ID/组内创建具有另一列前 n 行的滚动总和的列
- c# - 使用 C# 打印 Json 对象
- django - Wagtail:如何在下拉/自动完成列表中显示流场块选项/类型
- php - 根据两个日期计算下周周期
- django - 如何过滤每个帖子的相关对象 django
- javascript - 映射 JSON - 反应
- excel - 循环遍历单元格,但仅更改某些范围内的细节
- mongodb - 带有where条件的MongoDB插入