Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python key press to interrupt time.sleep()

Tags:

python-2.7

I have a program that spends a lot of time asleep in an endless loop, it checks in with another system API every 6 hours, and if there are changes does some stuff, if not goes back to sleep.

Without listing all the code, its pretty simple; I have

while True:
    do some stuff
    time.sleep(21600)

The only way to break this is with CTRL+C, but that seems ugly, is there a way to make another keypess interrupt the time.sleep() and use a graceful sys.exit()?

like image 941
Scalextrix Avatar asked Sep 15 '25 13:09

Scalextrix


1 Answers

I don't know if it's exactly what you are searching for, but I found a solution using pynput.

The following implementation is basically their reference implementation with your loop added.

from pynput import keyboard
from time import sleep

exit_flag = False

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(key.char))
    except AttributeError:
        print('special key {0} pressed'.format(key))

def on_release(key):
    print('{0} released'.format(key))

    if key == keyboard.Key.esc:
        global exit_flag
        exit_flag = True
        print("SET EXIT TO {}".format(exit_flag))
        return False

with keyboard.Listener(on_press=on_press,
    on_release=on_release) as listener:

    print("listen...")

    while not exit_flag:
        print("do something...")
        sleep(2)

    listener.join()

The workaround with the global exit condition is not the cleanest solution, but it does it's job.

EDIT:

I realized that you want to actually exit during sleep, which is also not possible with the implementation proposed. But would it be an option to catch the keyboard interrupt and perform the sys.exit() there? Would be quite a simple solution.

import time
import sys

while True:
    try:
        print("do something")
        time.sleep(10)
    except KeyboardInterrupt:
        print("to be able to exit script gracefully")
        sys.exit()
like image 107
conFusl Avatar answered Sep 17 '25 18:09

conFusl