树莓在睡眠时检测键盘输入



我在Raspbian中有一个python脚本,它无限循环并在主函数执行之间休眠15分钟。Main是线程的,但通常需要3秒才能运行。我不希望任何代码中断,当及时,下一个调用。在睡眠期间,我想检测按键'r'可选地启动另一个函数,可能也是线程。

我尝试了pynput模块,但得到了奇怪的暂停,似乎与线程和检查与VNC,我需要。我也尝试过在线程中进行常规的旧输入,但没有用户输入就无法让线程结束。

键盘模块在Windows中工作得很好,但在Raspbian中没有检测到键。我正在运行脚本使用sudo "sudo python3 scriptname.py"我真的不关心键检测是否使用线程是即时的。如果需要的话,我可以缩短我的睡眠周期,在大约一分钟后调用这个函数。我只是不能有一个大的停顿。

import time
import keyboard
import threading
def mainFunc():
print('does stuff')
def keyFunc():
print('do key detect stuff')
while True:
t1 = threading.Thread(target=mainFunc)
t1.start()
time.sleep(60)
t1.join()
keyboard.on_press_key("r", lambda _:keyFunc())
for _ in range(14):
time.sleep(60)
keyboard.unhook_all()

我认为可以帮助的一种方法是从datetime对象创建一个时间跨度持续时间,并将其用于主循环。

下面是我创建的一个示例。

from datetime import *
import time
import keyboard
import threading
#every 3 second function
x_start = datetime.now()
xSleep=3
def mainFunc():
newTime = datetime.now()
if(getTimeDiff(x_start,newTime)>xSleep):
setXStart(datetime.now())
return True
#every 15 minute function
y_start = datetime.now()
ySleep=900
def fifteenMinuteFunction():
newTime = datetime.now()
if(getTimeDiff(y_start,newTime)>ySleep):
setYStart(datetime.now())
return True 
#key press function (from pressing p)
def keyFunc():
print("do keystuff")
#calculate time difference since last call
def getTimeDiff(start, end):
span = end - start
#convert to string
spanStr = str(span)[0:7]
hours   = spanStr[0:1]
minutes = spanStr[2:4]
seconds = spanStr[5:7]
#convert to rounded int (seconds)
seconds = int(seconds) + (int(minutes) * 60) + (int(hours) * 60 * 60)
return int(seconds)
#set new start time for 3 second function
def setXStart(newTime):
global x_start 
x_start = newTime
#set new start tiem for 15 minute function
def setYStart(newTime):
global y_start 
y_start = newTime
#bind keyboard keys
keyboard.on_press_key("p", lambda _:keyFunc())                  # p do stuff function
while True:
if keyboard.is_pressed('x'):                                # exit keybind to x
exit()
elif mainFunc():
print("Doing thingy every "+str(xSleep)+" seconds")     # 3 seconds
elif fifteenMinuteFunction():
print("Doing thingy every "+str(ySleep)+" seconds")     # 15 mins
else:
time.sleep(.1)                                          

输出:

do keystuff
doing thingy every 3 seconds
do keystuff
doing thingy every 3 seconds
doing thingy every 3 seconds
....
doing thingy every 900 seconds
...
def inputDaemon():
while True:
x = input('r to reload')
if x == 'r': doTheFunc()
inpD = threading.Thread(target=inputDaemon)
inpD.daemon = True
inpD.start()

我最终使用的,它一直工作得很好。

相关内容

  • 没有找到相关文章

最新更新