python调用键盘_Liunx下使用Python读取键盘鼠标

在Linux下,可以使用Python直接读取dev/input目录下键盘和鼠标等设备文件,获取数据。

使用Python读取设备数据

例如读取键盘/dev/input/event3:

import struct

with open("/dev/input/event3", "rb") as f:

while True:

data = f.read(24)

time_sec, time_usec, type_, code, value = struct.unpack("QQHHi", data)

if type_ == 0:

continue

print("{}.{}\ttype={}\tcode={}\tvalue={}".format(time_sec, time_usec, type_, code, value))

使用root权限运行程序:

$ sudo python3 demo.py

1591000780.523814 type=4 code=4 value=589825

1591000780.523814 type=1 code=272 value=1

1591000780.691889 type=4 code=4 value=589825

1591000780.691889 type=1 code=272 value=0

1591000781.787812 type=2 code=0 value=1

1591000781.787812 type=2 code=1 value=-1

1591000781.803706 type=2 code=0 value=2

1591000781.843783 type=2 code=0 value=2

1591000781.883777 type=2 code=0 value=2

每一包数据由24个字节组成,其中timeval16字节,type2字节,code2字节,value四字节。C语言结构体如下:

// struct_timeval.h

struct timeval

{

__time_t tv_sec; /* Seconds. */

__suseconds_t tv_usec; /* Microseconds. */

};

// input.h

struct input_event {

struct timeval time;

__u16 type;

__u16 code;

__s32 value;

};

使用evtest查看输入设备数据

另外,如果只是想查看各输入设备的数据,可以使用evtest:

sudo apt install evtest

使用时直接以root权限运行evtest,输入对应编号即可,例如获取编码器数据:

# evtest

No device specified, trying to scan all of /dev/input/event*

Available devices:

/dev/input/event0: InputEmulator

/dev/input/event1: rotary-keys

/dev/input/event2: gpio-keys

Select the device event number [0-2]: 1

Input driver version is 1.0.1

Input device ID: bus 0x19 vendor 0x0 product 0x0 version 0x0

Input device name: "rotary-keys"

Supported events:

Event type 0 (EV_SYN)

Event type 2 (EV_REL)

Event code 0 (REL_X)

Properties:

Testing ... (interrupt to exit)

Event: time 1550141461.594735, type 2 (EV_REL), code 0 (REL_X), value -1

Event: time 1550141461.594735, -------------- SYN_REPORT ------------

Event: time 1550141461.825035, type 2 (EV_REL), code 0 (REL_X), value -1

Event: time 1550141461.825035, -------------- SYN_REPORT ------------

Event: time 1550141462.052871, type 2 (EV_REL), code 0 (REL_X), value -1

Event: time 1550141462.052871, -------------- SYN_REPORT ------------

Event: time 1550141462.199711, type 2 (EV_REL), code 0 (REL_X), value 1

Event: time 1550141462.199711, -------------- SYN_REPORT ------------

Event: time 1550141462.570028, type 2 (EV_REL), code 0 (REL_X), value 1

Event: time 1550141462.570028, -------------- SYN_REPORT ------------

Event: time 1550141464.492574, type 2 (EV_REL), code 0 (REL_X), value 1

Event: time 1550141464.492574, -------------- SYN_REPORT ------------

版权声明:本文为「txfly」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

原文链接:https://www.jianshu.com/p/4b207260c62e

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值