-
Notifications
You must be signed in to change notification settings - Fork 4
/
RecordClickWithRedis.py
73 lines (65 loc) · 2.17 KB
/
RecordClickWithRedis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from evdev import InputDevice
from select import select
import redis
import time
import os
from configparser import ConfigParser
path = '/home/kcp/.config/app-conf/key-record/main.conf'
def detectInputKey(eventNum, conn):
''' 记录每个按键次数以及总按键数 '''
try:
dev = InputDevice('/dev/input/event'+str(eventNum))
except:
logError('event config error')
is_event_correct = False
try:
log('Ready to listen ... ')
while True:
today = time.strftime('%Y-%m-%d',time.localtime(time.time()))
# 如果 event错了, 下面直接阻塞掉
select([dev], [], [])
if is_event_correct == False:
log('\033[0;32mSuccessful startup\033[0m')
is_event_correct = True
for event in dev.read():
if event.value == 1 and event.code != 0:
conn.zincrby(today, event.code)
conn.incr('all-'+today)
conn.zadd('detail-'+today, str(time.time()), event.code)
except:
logError('Error!! Device has been removed Or Application has been interrupted')
def get_conf():
# 加载配置文件
global path
if not os.path.exists(path) :
logError('Please refer to Readme.md initialization configuration')
exit(1)
cf = ConfigParser()
cf.read(path)
return cf
def get_conn():
cf = get_conf()
host = cf.get('redis', 'host')
port = cf.get('redis', 'port')
db = cf.get('redis', 'db')
password = cf.get('redis', 'password')
if password == '':
conn = redis.Redis(host=host, port=port, db=db)
else:
conn = redis.Redis(host=host, port=port, db=db, password=password)
try:
conn.ping()
return conn
except:
logError('Redis connection failed')
exit(1)
def logError(origin='', end=None):
log('\033[0;31m'+origin+'\033[0m', end=end)
def log(origin=None, end=None):
print(time.strftime('%Y-%m-%d',time.localtime(time.time())), origin, end=end)
def main():
global redis
eventNum = get_conf().get('event', 'key')
detectInputKey(eventNum, get_conn())
if __name__=="__main__":
main()