rainydaymatt
rainydaymatt

Reputation: 630

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.

Upvotes: 0

Views: 10783

Answers (2)

whitebeard
whitebeard

Reputation: 1131

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

Upvotes: 4

jteezy14
jteezy14

Reputation: 466

The last three lines I added will allow you to break out of the loop with any key being pressed. Dont forget the import of msvcrt

import time, win32api
import msvcrt
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))
    if msvcrt.kbhit():
        if ord(msvcrt.getch()) != None:
            break

Upvotes: 3

Related Questions