Threading поможет вам здесь.Как говорит Модуль недели Python (PyMOTW) :
Использование потоков позволяет программе одновременно выполнять несколько операций в одном и том же пространстве процесса.
В вашем случае вы все еще можете прочитать ввод с клавиатуры в цикле блокировки в своем собственном потоке и позволить функции сна проверять время в другом потоке, не блокируясь read_loop в evdev.Просто установите для 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()