这次我想知道以下情况有哪些可能的解决方案:我让我的笔记本电脑使用我已经在这里发布的python脚本读取原始鼠标数据(Ubuntu OS)。它有一个方法,该方法读取鼠标文件并从中提取 x,y 数据。a while true 循环使用此方法将数据放入数组中。当我使用时间计数器在一段时间后停止读取时,脚本将数据放入 Excel 文件中。我现在需要的是一个暂停数据流的选项,即在不创建数据的情况下更改鼠标位置,然后恢复它。 我想有一些东西来停止阅读并将其写入 excel。
import struct
import matplotlib.pyplot as plt
import numpy as np
import xlsxwriter
import time
from drawnow import *
workbook = xlsxwriter.Workbook('/path/test.xlsx')
worksheet = workbook.add_worksheet()
file = open( "/dev/input/mouse2", "rb" );
test = [(0,0,0)]
plt.ion()
def makeFig():
plt.plot(test)
#plt.show()
def getMouseEvent():
buf = file.read(3);
button = ord( buf[0] );
bLeft = button & 0x1;
x,y = struct.unpack( "bb", buf[1:] )
_zeit = time.time()-test[-1][-1]
print ("x: %d, y: %d, Zeit: %dn" % (x, y, _zeit) )
return x,y, _zeit
zeit = time.time()
warte = 0
while warte < 20:
test.append(getMouseEvent())
warte = time.time()-zeit
row = 1
col = 0
worksheet.write(0,0, 'x-richtung')
worksheet.write('C1', 'Zeit')
for x, y , t in (test):
worksheet.write(row, col, x)
worksheet.write(row, col + 1, y)
worksheet.write(row, col + 2, t)
row += 1
chart = workbook.add_chart({'type': 'line'})
chart.add_series({'values': '=Sheet1!$A$1:$A$'+str(len(test))})
worksheet.insert_chart('D2', chart)
workbook.close()
#drawnow(makeFig)
#plt.pause(.00001)
file.close();
拥有类似"暂停/取消暂停的命中空间"之类的东西会很棒。q结束并保存",但我不知道该怎么做。任何想法都会很好:)哦,我尝试使用 matplotlib 绘制数据,这有效,但这是未来改进的东西;)
这是标准线程模块的示例 - 我实际上不知道它的响应速度如何。此外,如果您想根据全局热键而不是脚本暂停或开始输入,这将取决于您的桌面环境 - 我只使用了xlib
但应该有一个 python 包装器漂浮在某处。
import threading
import struct
data =[]
file = open("/dev/input/mouse0", "rb")
e=threading.Event()
def getMouseEvent():
buf = file.read(3);
#python 2 & 3 compatibility
button = buf[0] if isinstance(buf[0], int) else ord(buf[0])
bLeft = button & 0x1;
bMiddle = ( button & 0x4 ) > 0;
bRight = ( button & 0x2 ) > 0;
x,y = struct.unpack( "bb", buf[1:] );
return "L:%d, M: %d, R: %d, x: %d, y: %dn" % (bLeft,bMiddle,bRight, x, y)
def mouseCollect():
global e
#this will wait while e is False (without breaking the loop)
#and loop while e is True
while e.wait():
#do something with MouseEvent data, like append to an array, or redirect to pipe etc.
data.append(getMouseEvent())
mouseCollectThread = threading.Thread(target=mouseCollect)
mouseCollectThread.start()
#toggle mouseCollect with any keyboard input
#type "q" or "quit" to quit.
while True:
x = input()
if x.lower() in ['quit', 'q', 'exit']:
mouseCollectThread._stop()
file.close()
break
elif x:
e.clear() if e.isSet() else e.set()
编辑:我在e.isSet之后缺少()