作爲一個起點,基於a solution by Treviño,這裏是一個快速和(大部分)髒捕獲鍵盤事件並報告計時方式:
import struct
FORMAT = 'llHHI'
EVENT_SIZE = struct.calcsize(FORMAT)
EV_KEY = 0x01
KEY_DOWN = 1
KEY_AUTO = 2
KEY_UP = 0
devname = "/dev/input/event0"
def dt(sec_a, usec_a, sec_b, usec_b):
return (sec_a+usec_a/1000000.) - (sec_b+usec_b/1000000)
with open(devname, "rb") as infile:
kdtime = {}
while True:
event = infile.read(EVENT_SIZE)
(tv_sec, tv_usec, typ, code, value) = struct.unpack(FORMAT, event)
if typ == EV_KEY:
if value == KEY_DOWN:
kdtime[code] = (tv_sec, tv_usec)
if value == KEY_UP and code in kdtime:
print(code, dt(tv_sec, tv_usec, *kdtime[code]))
del kdtime[code] # Not strictly required
從Documentation/input/input.txt事件是由內核報告爲:
struct input_event {
struct timeval time;
unsigned short type;
unsigned short code;
unsigned int value;
};
timeval結構是是反過來在bits/time.h
定義爲:
struct timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* Microseconds. */
};
因此,事件的相應Python結構格式爲llHHI
。一旦你有了這些,你必須循環讀取類型爲EV_KEY
的事件,然後記住關鍵時間,並在返回鍵入代碼時計算按鍵時間。
請注意,您不能假定按鍵事件與前一按鍵事件相匹配(請考慮一次按幾個按鍵)。因此,我會跟蹤字典中的關鍵代碼和相應的按鍵時間。顯然,你將不得不適應你的需求。但正如我所說,這只是一個起點。
[格式爲/dev/input/event\*?](http://stackoverflow.com/questions/5060710/format-of-dev-input-event) – 2015-04-04 20:59:43
@SylvainLeroux:它看起來像一個比你所鏈接的問題更具體的問題。 – jfs 2015-04-05 11:56:59
@ J.F.Sebastian我自己同意這個問題。但我認爲一些答案有必要的信息來解決OP問題。無論如何,你可能是對的:所以,我已經綜合了所有這一切,並將其作爲答案發布在此處。 – 2015-04-05 12:46:53