在真循环中捕获 USB 事件



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

线程将在这里为您提供帮助。正如本周Python Module (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()

相关内容

  • 没有找到相关文章

最新更新