'Stop a system from going to sleep with Python
I am currently working on a small program that stops a system from going inactive with Python (I know you can prevent systems from going to sleep but I am just doing it for fun). Currently I am using pyautogui to simulate mouse movement by moving the cursor to a random X and Y coordinate every iteration. However, it seems that this isn't actually simulating mouse movement as when using it my system and applications go into idle mode even though the mouse is moving around the screen.
Code:
import pyautogui
import keyboard
import random
import time
import sys
def main():
run()
def run():
print(welcomeMessage())
time.sleep(5)
totalDistance = 0
run = True
randX = genRandX()
randY = genRandY()
totalDistance += (randX+randY)
pyautogui.moveTo(randX, randY)
while run:
mouseMoved(randX, randY, totalDistance)
try:
#time.sleep(3)
randX = genRandX()
randY = genRandY()
totalDistance += (randX+randY)
moveTheMouse(randX, randY)
print(f"Mouse move to - X: {randX}, Y: {randY}")
except:
print("Mouse not moved due to failsafe") # Shouldn't happen
def genRandX():
return random.randint(100, 900)
def genRandY():
return random.randint(100, 900)
def moveTheMouse(x, y):
pyautogui.moveTo(x, y)
def welcomeMessage():
otherMessage = "\nMove your mouse around to stop"
space = "\n"
return "This program will move your cursor to a random coordinate every 5 seconds" + otherMessage + space
def mouseMoved(currentX, currentY, totalDistance):
# This function stops program when mouse is moved by user
currentPos = pyautogui.position()
supposedCurrentX = currentPos.x
supposedCurrentY = currentPos.y
xDifference = currentX - supposedCurrentX
yDifference = currentY - supposedCurrentY
if xDifference > 5 or xDifference < -5 or yDifference > 5 or yDifference < -5: # Allows for slight movement
print(f"\nProgram closing! Total distance covered: {totalDistance} pixels")
time.sleep(4)
sys.exit()
#if supposedCurrentX != currentX or supposedCurrentY != currentY:
#sys.exit()
main()
I would like to know if there is a way to legitimately simulate mouse movement with Python that would prevent systems and/or applications from going into an inactive state. Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
