Skip to content
Advertisement

Raspbian detect keyboard input while sleeping

I have a python script in Raspbian that loops indefinitely and sleeps for 15 minutes between the main function executions. Main is threaded but usually takes 3 seconds to run. I don’t want any code to interrupt, when in time, the next call is made. During sleep I would like to detect keypress ‘r’ to optionally start another func, possibly threaded as well.

I tried the pynput module but got weird pauses that seem to be related to threading and checking in with VNC, that I need. I also tried regular old input inside a thread but couldn’t get the thread to end without user input.

The keyboard module works great in Windows but detects no keys for Raspbian. I am running the script using sudo “sudo python3 scriptname.py” I don’t really care if the key detection is instant by using threads. I can chop up my sleep cycle to call the function after a minute or so if needed. I just can’t have a big pause.

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()

Advertisement

Answer

def inputDaemon():
    while True:
        x = input('r to reload')
        if x == 'r': doTheFunc()

inpD = threading.Thread(target=inputDaemon)
inpD.daemon = True
inpD.start()

What I eventually used and it’s been working fine.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement