我希望在“while True”循环中捕获单个 USB 键盘事件,该循环还包括一个计时器功能。Evdev 接近我所需要的,但它的 device.read_loop 不允许包含时钟功能 - 它是一个闭环。关于如何捕获一个我可以在检查时控制的 USB 键盘事件的任何想法?我使用的是 Python 3.4,所以 asyncio 不是一个选项。谢谢你。
问问题
392 次
1 回答
0
线程将在这里为您提供帮助。正如Python 本周模块 (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()
于 2019-05-24T15:42:59.853 回答