I need to run a code for hours, and the computer I am working with has a (forced and unchangeable) screensaver policy. (It locks after 10 minutes). What can I do to prevent it? Is there any line of code to prevent that?
This worked for me. I'll just leave it here so people can use it.
import ctypes
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002) #this will prevent the screen saver or sleep.
## your code and operations
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000) #set the setting back to normal
You can prevent screen saver by moving mouse cursor on a fixed period of time, below function can handle cursor moving.
import win32api
import random
def wakeup():
win32api.SetCursorPos((random.choice(range(100)),random.choice(range(100))))
This is a coded solution that you can place in your program (also works for Mac users):
pip3 install pyautogui
https://pypi.org/project/PyAutoGUI/ (Reference)
import pyautogui
import time
def mouse_move():
while True:
pyautogui.moveTo(100, 100, duration = 1) # move the mouse
time.sleep(60) # Every 1 min
pyautogui.moveTo(50, 100, duration = 1) # move the mouse
mouse_move()
Or, without the while loop, run it when required if your program is already within a while loop:
def mouse_move():
pyautogui.moveTo(50, 100, duration = 1) # move the mouse
mouse_move()
Related
I have been learning python recently and decided to learn more about pyautogui, what you see down below is a macro of mine. My question is simple; is there a way to let this macro run in a specific window. For example: I want this macro to run in google chrome while I am in discord chatting with my friends (text channel so I'm not in the google chrome window). (Ignore my sloppy method of writing code)
import pyautogui
import random
import time
import mouse
#############################
tijd = 0
actief = 0
float (actief)
#############################
while not mouse.is_pressed('right'):
time.sleep(0.01)
bank_x1, bank_y1 = pyautogui.position()
time.sleep (0.5)
while not mouse.is_pressed('right'):
time.sleep(0.01)
bank_x2, bank_y2 = pyautogui.position()
print ("{} {} {} {}".format(bank_x1,bank_x2,bank_y1,bank_y2))
#############################
lijst = [[bank_x1,bank_x2,bank_y1,bank_y2,200,243],[1203,1236,721,749,23,49],[390,422,112,140,22,46]]
while not mouse.is_pressed('middle') or actief > tijd:
for i in range(0, 4):
x = random.randint(lijst[i][0], lijst[i][1])
y = random.randint(lijst[i][2], lijst[i][3])
pyautogui.moveTo(x, y)
wacht = random.randint(lijst[i][4], lijst[i][5]) / 100
time.sleep(wacht)
str (actief_str)
pyautogui.click()
pyautogui.press('esc')
No. Not with pyautogui.
Pyautogui simulates actual keyboard and mouse input to the system, not to a specific window. Thus, it will always act exactly the same as if you were pressing the keys and clicking the mouse yourself. So, no. You cannot use it to send keystrokes to background applications. The keystrokes will always effect the window that is focused, just as they do when you physically input them with a keyboard or mouse.
This question shows how you could achieve it with winapi, but it is much more complicated and less user-friendly than pyautogui.
I'm building a headless soundboard using Raspberry Pi, and as such need a way to launch the script I'm using on boot. The program was edited and tested using the default editor Pi shot up, Thonny, and everything seems to run as intended. The buttons I'm using all play the sounds I expect them to, no issues.
I went ahead and edited rc.local to run the script as soon as the Pi boots (specifically, I added sudo python /filepath/soundboard.py & above exit 0), which it does. It seems to run identically to the way it did using Thonny, but sound cuts off after about 5 seconds, even if no buttons are pressed. When I run it directly through the command line, the same issue occurs.
The code here has been compressed, as there is more than one button, but they all use the same line.
import pygame
import random
import glob
from gpiozero import Button
import time
pygame.init()
while True:
n = glob.glob('/filepath/*.wav')
btn_0 = Button(8)
btn_0.when_pressed = pygame.mixer.stop
btn_0.when.held = lambda: pygame.mixer.Sound(random.choice(n)).play()
As far as I can tell, the while loop continues to run the program, but pressing buttons does nothing. Also, since adding the loop, the code dumps a Traceback, showing the error
gpiozero.exc.GPIOPinInUse: pin 8 is already in use by <gpiozero.Button objext on pin GPIO8, pull_up=True, is_active=False>
which might have something to do with my issue? btn_0 isn't the only button to have two functions assigned to it, but the only one to throw up this error, no matter what pin I use. The error doesn't appear if I remove the loop from the code.
You create btn_0 in an infinit while loop again and again. In the second iteration btn_0 is probably the first button that is created again. But pin 8 (which should be used for the button) has been assigned to the old instance of btn_0 in the last iteration.
You should move the glob.glob statement and the button initialization outside of the While loop. If the while loop is necessary to keep you program running place it below the initialization code and iterate over nop ore pause statements (whatever works).
If pygame.init starts it own looped thread you do not need a while loop at the end at all.
I don't know anything about pygame, so the last statement is just a guess.
Example:
import pygame
import random
import glob
from gpiozero import Button
import time
pygame.init()
n = glob.glob('/filepath/*.wav')
btn_0 = Button(8)
btn_0.when_pressed = pygame.mixer.stop
btn_0.when.held = lambda: pygame.mixer.Sound(random.choice(n)).play()
while True:
nop
I have some code as follows:
# My code here
turtle.bye()
After that, is there any way I can reopen the turtle window.
I know you can do turtle.clearscreen() but that does not close the turtle window.
I will accept any answer which allows me to close the turtle graphics window and then reopen it without opening and running another python program to do this.
Thank you in advance
I've seen situations where the approach of #LukeTimmons worked but not always reliably and not in every situation. Give this solution a try:
import time
import turtle
turtle.dot(200, 'green')
time.sleep(2)
turtle.bye()
# These two lines (indirectly) resurrect turtle environment after turtle.bye()
turtle.Turtle._screen = None # force recreation of singleton Screen object
turtle.TurtleScreen._RUNNING = True # only set upon TurtleScreen() definition
turtle.dot(200, 'red')
turtle.mainloop()
It resets two flags that keep turtle from starting up again. It may be safer to create your own turtle after restart rather than use the default turtle which may point back to the departed environment.
There may be other ways but this is the only way I know.
from turtle import *
def turtle1():
#Your code here
turtle1()
turtle.bye()
turtle1()
This should re-run your code without re-typing it.
I am testing out pyglet for usage in a larger project, and apparently pyglet recommends/wants you to use it's own loop (with pyglet.app.run())
This is a something I don't want, for reasons of compatibility of other packages and also to not have to rewrite the entire program structure.
Here I have prototype code stuck together from different parts and tutorials and docs.
It runs for 5-15 iterations and then just freezes, not printing anything and also not doing any draw updates.
from __future__ import division, print_function
import sys
import pyglet
window = pyglet.window.Window(800, 800, resizable=True)
window.set_caption('Pyglet Testing')
window.flip()
image = pyglet.resource.image('Sprites/scout.png')
def draw(dt):
image.blit(700-dt, 400)
while not window.has_exit:
dt = pyglet.clock.tick()
window.dispatch_events()
window.clear()
draw(dt)
window.flip()
print(dt)
My suspicion is that I have done nothing to catch events and handle them, so at a certain point it just overflows with events and blocks the whole thing. I couldn't understand how to do this however, and getting overflowed with events in under 1 second seems a bit much.
Any help?
Basically what you are doing is sending as many image.blit(...) commands to the window, until the pc probably can't handle it anymore.
For instance, if you change your code like this:
add this code:
import time
from time import sleep
change code:
def draw(dt):
image.blit(700-dt, 400)
sleep(0.1) #insert this line
When executing the modified code, you will notice that it does not freeze and that the output dt is around 0.11 seconds, which is the number of seconds since the last "tick" = the time slept (0.1 second) + the remainder time (clear window, display new frame ...)
I'm trying to make a simple python program that will detect if either my keyboard or mouse are idle, and if so to move the mouse.. this is to circumvent an idle logout timeout on a macbook.. I can't change these settings as they're policies pushed by my employer. It's set to like 3 minutes which is extremely annoying. I have it working for mouse inactivity, but not keyboard
How would I, or what library would i use to detect if no keyboard activity has happened?
#!/usr/bin/env python
import pyautogui
import time
from random import randrange
def timer():
get_time = int(time.time())
return get_time
def main():
while True:
snapshot = { "time" : timer(), "position" : pyautogui.position() }
time.sleep(5)
if snapshot["position"] == pyautogui.position():
pyautogui.moveTo(400,randrange(1,50))
else:
pass
main()
I did something similar here https://gitlab.com/shakerloops/shakerloops
But I don't think I was detecting key events.
Even so, you could theoretically just use keyevent from pygame or wxpython. both can detect keyboard events without actually launching a GUI. Example:
https://gitlab.com/makerbox/alluvial/raw/master/usr/local/bin/alluvial/alluvial.py
Those two combined ought to work!
I don't know if this is relevant to your case and I know it doesn't work totally for mac as I did it on Windows but I'll give you an idea how I managed it.
The reason is that although the keyboard package works for mac, the mouse package is available only for windows and Unix.
You mentioned that detecting mouse inactivity is working and I was facing the same issue (able to detect mouse inactivity but not keyboard inactivity) so I tied keyboard activity with mouse activity.
Practically this means that whenever I use the keyboard, the mouse moves around like a few pixels in different directions. This will create mouse activity that will signal the program that the keyboard is active as well (I chose a few keys that I regularly use to make the mouse move around).
import mouse
import keyboard
keyboard.add_hotkey("space", lambda: mouse.move(4, 5, absolute=False, duration=0.01))
keyboard.add_hotkey("ctrl", lambda: mouse.move(-2, -8, absolute=False, duration=0.01))
keyboard.add_hotkey("shift", lambda: mouse.move(3, -4, absolute=False, duration=0.01))
keyboard.add_hotkey("alt", lambda: mouse.move(-7, 2, absolute=False, duration=0.01))
keyboard.add_hotkey("e", lambda: mouse.move(-3, -6, absolute=False, duration=0.01))
Recently was trying to do something similar that involved doing an action after idling for a certain amount of time. Here's what I used. It detects both keyboard and mouse actions in any window:
from pynput.keyboard import Key, Listener
import time
import pyautogui
idle_action = 60 ##number of seconds for idle
idled_time = [time.time()] ##use a list so no global/local variable conflict happens
idle_pos = [pyautogui.position()]
def update_idle(key):
idled_time.append(time.time())
idle_pos.append(pyautogui.position())
with Listener(on_press=update_idle) as listener:
while True:
for i in range(len(idle_pos)-1): ##only the latest value in each list is the actual value
del idle_pos[0]
for i in range(len(idled_time)-1):
del idled_time[0]
current_pos = pyautogui.position()
if current_pos!=idle_pos[0]:
update_idle(None)
elif time.time()-idled_time[0]>idle_action:
do_what_you_want_to_do() #<----