Search code examples
pythoninfinite-loop

Interrupt Python infinite while loop with key press


I'm writing a simple script to prevent my computer from falling asleep (don't have admin privileges), and it centers around an infinite loop caused by a "while True" line:

import time, win32api
cursorX = 0
cursorY = 0
while True:
    cursorX, cursorY = win32api.GetCursorPos()
    time.sleep(600)
    cursorX = cursorX + 10
    win32api.SetCursorPos((cursorX,cursorY))
    cursorX, cursorY = win32api.GetCursorPos()
    time.sleep(600)
    cursorX = cursorX - 10
    win32api.SetCursorPos((cursorX,cursorY))

Now, I can interrupt this with a simple Ctrl + C, but I'd like to kill it more cleanly than that. Is there a simple way to write a condition to wait for a key press to kill the loop? I'm guessing it might involve an event, about which I know little.


Solution

  • A way to clean up the use of CTRL-C is to use try-except to catch the KeyboardInterrupt like:

    try:
        while True:
            ...
            ...
    except KeyboardInterrupt:
        exit