While True Loop中的USB事件捕获

时间:2019-04-30 02:50:39

标签: python usb evdev

我希望在“ while True”循环中捕获单个USB键盘事件,该循环还包括计时器功能。 Evdev接近我的需要,但它是device.read_loop不允许包含时钟功能-这是一个闭环。关于如何捕获单个USB键盘事件(在检查时可以控制)的任何想法?我正在使用Python 3.4,因此无法选择asyncio。谢谢。

1 个答案:

答案 0 :(得分:0)

线程将在这里为您提供帮助。正如Python Module of the Week (PyMOTW)所说:

  

使用线程可以使程序同时运行多个操作   在相同的处理空间中。

在您的情况下,您仍然可以在自己的线程的阻塞循环中读取键盘输入,并让sleep函数检查另一个线程中的时间,而不会被evdev的read_loop阻塞。只需将radio_sleep_time设置为要等到收音机进入睡眠状态的秒数即可(您可以使用分钟,而radio_sleep_time = 4 * 60可以使用4分钟)。

from time import time
from threading import Thread
from evdev import *

radio_sleep_time = 4  # sleep time for radio in seconds
device = InputDevice('/dev/input/event3')  # pick the right keyboard you want to use


def read_kb():
    for event in device.read_loop():
        # only use key events AND only key down can be changed depending on your use case.
        if event.type == ecodes.EV_KEY and event.value == 1:
            keyevent = categorize(event)  # just used here to have something nice to print
            print(keyevent)  # print key pressed event


def wait_loop():
    pass  # whatever radio is doing when its waiting to sleep if anything.


class Time1(Thread):
    def run(self):
        while True:
            read_kb()


class Time2(Thread):
    def run(self):
        t0 = time()  # starting time
        # time() (current time) - t0 (starting time) gives us the time elapsed since starting
        while not time() - t0 > radio_sleep_time:  # loop until time passed is greater than sleep_time
            wait_loop()  # do sleep stuff
        print(time() - t0, ">", radio_sleep_time)
        print("SLEEP")
        # sleep radio here
        # but continue to listen to keyboard


Time1().start()
Time2().start()