0

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.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

This isn't very portable; it wouldn't work with non-windows machines!
Agreed, but none of this code would work on non-windows machines as it relies on the win32api

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.