You can do this using a while loop like this:

from time import sleep
import pyautogui

pyautogui.PAUSE = 2.5

while True:
    sleep(2)

    pyautogui.moveTo(1171, 458)
    pyautogui.click()
    pyautogui.moveTo(1123, 403)
    pyautogui.click()

If you don't want the script to sleep for 2 seconds every time, you can move the sleep(2) above the while True: and remove the spaces behind the sleep(2)

Answer from ZiyadCodes on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › help with loop in pyautogui!
r/learnpython on Reddit: Help with loop in Pyautogui!
June 24, 2023 -

Hi guys, i create script on python and i want that it repeat endlessly. I dont know have implemented loop for this because always appear mistake :( I will show code below.

import pyautogui
import time
print(pyautogui.size())
pyautogui.moveTo(1800,1000) 
pyautogui.click() 
pyautogui.typewrite('F4F') 
pyautogui.moveTo(1890,1000) 
pyautogui.click() 
time.sleep(3)
pyautogui.moveTo(1800,1000) 
pyautogui.click() 
pyautogui.typewrite('Oddam!') 
pyautogui.moveTo(1890,1000) 
pyautogui.click() 
time.sleep(3)
pyautogui.moveTo(1800,1000) 
pyautogui.click() 
pyautogui.typewrite('ODDAM OBSERWACJE') 
pyautogui.moveTo(1890,1000) 
pyautogui.click() 
time.sleep(3)
pyautogui.moveTo(1800,1000)

Please help me with this homies.

Discussions

How can I loop this code every 20 secondes?

The time modele offers a method you want:

import time

time.sleep(20)

time.sleep(20) a will delay your code by 20 seconds Documentation

And you can put you code into a while-loop:

import time 

while True:
    # do something
    time.sleep(20)
    
    # if you want to exit the loop you can use this keyword:
    break

The keyword break stops the while-loop.

Alternatively, you could solve the problem this way:

go_ahead = True
while go_ahead:
    # do something
    time.sleep(20)
    
    go_ahead = False
More on reddit.com
🌐 r/learnpython
4
1
April 1, 2020
python - how to break the while loop in pyautogui by clicking on specific keyboard key - Stack Overflow
i want to break my code by clicking specific key because its impossible to do it with mouse (mouse is being used by program). import pyautogui import time from mss import mss start_x = 610 start_... More on stackoverflow.com
🌐 stackoverflow.com
May 4, 2019
python - Pyautogui Script and Looping - Stack Overflow
Made a script to copy info to an API. How do i repeat this script to run a certain number of times? Sorry, just started playing around with python for work so i'm not too sure of what i'm doing jus... More on stackoverflow.com
🌐 stackoverflow.com
August 20, 2020
python - How can I loop PyAutoGUI's locateCenterOnScreen until the image is found? - Stack Overflow
Based on Why can't pyautogui locate my image although the code seems to be just fine? it seems like instead of running my code once, perhaps I should loop the following function until the image is detected. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 61177250 › pyautogui-in-for-loop-python
PYAUTOGUI IN FOR LOOP Python - Stack Overflow
import pyautogui,os directory = 'C:\\Users\\johna\\Desktop\\pdfs' x=226 y=280 for filename in os.listdir(directory): if filename.endswith('.txt'): pyautogui.click(x,y) pyautogui.press('f2') pyautogui.hotkey('ctrl','c') y=y+30 pyautogui.moveTo(107,559,duration=2) pyautogui.click() pyautogui.hotkey('ctrl','v')
🌐
Automate the Boring Stuff
automatetheboringstuff.com › 1e › chapter18
Controlling the Keyboard and Mouse with GUI Automation
The code then loops through 200 numbers and adds each number to numbers, along with a newline. After pyperclip.copy(numbers), the clipboard will be loaded with 200 lines of numbers. Open a new file editor window and paste the text into it. This will give you a large text window to try scrolling in.
🌐
Python Forum
python-forum.io › thread-21534.html
pyautogui while loop
October 3, 2019 - Having an issue with my script i am trying to get the script to wait until an image is no longer displayed on screen to continue to the next task. Here is what i have hangs up and just keeps posting Please wait. invalid = pyautogui.locateOnScreen('l...
🌐
PyAutoGUI
pyautogui.readthedocs.io › en › latest › mouse.html
Mouse Control Functions — PyAutoGUI documentation
#! python3 import pyautogui, sys print('Press Ctrl-C to quit.') try: while True: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr, end='') print('\b' * len(positionStr), end='', flush=True) except KeyboardInterrupt: print('\n')
🌐
Google Groups
groups.google.com › g › python-brasil › c › WJOoKY5mPWo
Como faço criar um loop para escrever um nome (em numeral), a cada loop _ pyautogui
Mas é isso! A execução fica em loop até que eu pare ela. ... pyautogui.write ('005') # escrevendo o número da página do ebook.
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › how can i loop this code every 20 secondes?
r/learnpython on Reddit: How can I loop this code every 20 secondes?
April 1, 2020 -

I have made this code and for it to function It needs to be looped every 20 secondes.

import pyautogui
import cv2
pyautogui.FAILSAFE = True

pyautogui.dragTo(1095, 568, 2)
pyautogui.click(1095, 568, 5) #De 0,01 knop
pyautogui.dragTo(720, 644, 2)
pyautogui.click(720, 644) #De ct knop
if pyautogui.locateOnScreen("ctt.png", confidence=0.4, region=(1220, 487, 32, 30)):
    pyautogui.dragTo(1018, 568, 2)
    pyautogui.click(1018, 563) #De clear knop
else:
    pyautogui.dragTo(1440, 563, 2)
    pyautogui.click(1440, 563) #De x2 knop

And is it possible every every loop so every 20 secondes to look if the image is found? ``pyautogui.locateOnScreen("ctt.png", confidence=0.4, region=(1220, 487, 32, 30))``

🌐
GitHub
github.com › asweigart › pyautogui › issues › 61
locateOnAllScreen not working on loop · Issue #61 · asweigart/pyautogui
October 23, 2015 - Loop : for tick in pyautogui.locateAllOnScreen('ticket.png'): print tick ·
🌐
Linus Tech Tips
linustechtips.com › software › programming
Python, Pyautogui, my while true loop doesn't continue - Programming - Linus Tech Tips
January 4, 2021 - The code works once even though I have it set in a loop, what do I need to change to make it work.
🌐
Sololearn
sololearn.com › en › Discuss › 2258062 › need-help-to-end-loop-using-keyboard-shortcut
need help to end loop using keyboard shortcut | Sololearn: Learn to code for FREE!
### Hi guys, I need help to end the run_porgram() loop using a keyboard shortcut since my program is running in another window other than terminal using Ctrl+C is not working, I can set how many times it should run but sometimes I need to stop it earlier. ### import time import pyautogui, sys from time import sleep def search_cycle_increase(): pyautogui.click(1078, 799) # search sleep(0.8) pyautogui.click(1183, 743) # buy now sleep(0.12) pyautogui.click(724, 530) # ok sleep(0.12) pyautogui.click(123, 215) # back sleep(0.12) pyautogui.press('k') sleep(0.12) def search_cycle_decrease(): pyautogu
🌐
YouTube
youtube.com › watch
Troubleshooting Pyautogui Loop Issues: Why Your Loop Might Be Skipping Items - YouTube
Discover how to fix skipping issues in your Pyautogui loops by adjusting sleep times. This guide explains the importance of timing in automation scripts.---T...
Published   September 20, 2025
Views   0
🌐
Stack Overflow
stackoverflow.com › questions › 63496581 › pyautogui-script-and-looping
python - Pyautogui Script and Looping - Stack Overflow
August 20, 2020 - Possible duplicate question: stackoverflow.com/questions/10440493/for-loops-novice ... This will run n times. import pyautogui as pag import time time.sleep (3) for i in range(n): pag.click(448, 98, interval = 0.25) #click NEW bookmark pag.hotkey('ctrl', 'tab') #switch to spreadsheet; must be on the correct cell pag.hotkey('ctrl', 'c', interval=0.25) #copies first name from spreadsheet pag.press('tab') #move to last name cell before switch to API pag.hotkey('ctrl', 'tab') #switch back to API pag.scroll(50) #scrolls to view recruiter pag.click(192, 297) #clicks first name box to have a place to press enter pag.press('enter') #saves entered information
Top answer
1 of 3
4

From the documentation:

Like the enchanted brooms from the Sorcerer’s Apprentice programmed to keep filling (and then overfilling) the bath with water, a bug in your program could make it go out of control. It’s hard to use the mouse to close a program if the mouse cursor is moving around on its own.

As a safety feature, a fail-safe feature is enabled by default. When a PyAutoGUI function is called, if the mouse is in any of the four corners of the primary monitor, they will raise a pyautogui.FailSafeException. There is a one-tenth second delay after calling every PyAutoGUI functions to give the user time to slam the mouse into a corner to trigger the fail safe.

You can disable this failsafe by setting pyautogui.FAILSAFE = False. I HIGHLY RECOMMEND YOU DO NOT DISABLE THE FAILSAFE.

The tenth-second delay is set by the pyautogui.PAUSE setting, which is 0.1 by default. You can change this value. There is also a pyautogui.DARWIN_CATCH_UP_TIME setting which adds an additional delay on macOS after keyboard and mouse events, since the operating system appears to need a delay after PyAutoGUI issues these events. It is set to 0.01 by default, adding an additional hundredth-second delay.

Therefore, if you want to "speed up" your loop, you can reduce the pyautogui.PAUSE value. However, keep in mind, this will prevent you from having time to activate the failsafe if you need it.

2 of 3
1

Set pyautogui.PAUSE to a small number. The default is 0.1 secs between actions. Here is example code:

import pyautogui
pyautogui.PAUSE = 0.01  # can be a float or an integer

This will increase the speed of your spambot/autoclicker/anything.

🌐
Reddit
reddit.com › r/learnpython › pynput in a loop with pyautogui
r/learnpython on Reddit: Pynput in a loop with pyautogui
January 16, 2018 -

I'm trying to make custom macro keys with pynput and pyautogui but I can't get pynput to work in a loop without errors or unexpected results. I've tried digging through the github code but I can't figure out how it all works.

My end goal is to be able to hit a key or combination of keys on the keyboard (e.g. Numpad_1 or page_up or ctrl+h) and it run a script with pyautogui like a custom macro. I could do this with a program like AHK but I want to do it with python for more flexibility and familiarity. I don't mind doing a bit of Java if I need to or if there's a better way to do it in Java.

I'm running Python 3.4.3 on Windows 10 from the command prompt but I don't want the command prompt focused so I can run the macro while running another program like Photoshop or something. Here's my code so far that doesn't seem to work:

import time
from pynput import keyboard

def on_press(key):
    try:
        print('{}'.format(key.char))
    except AttributeError:
        print('{}'.format(key))

def on_release(key):
    if key == keyboard.Key.delete:
        # Stop listener
        return False

# Collect events until released
'''
with keyboard.Listener(on_press = on_press, on_release = on_release) as listener:
    listener.join()
'''

listener = keyboard.Listener(on_press = on_press, on_release = on_release)
listener.start()

i = 0

while True:
    listener.join()
    time.sleep(1)
    print(str(i) + ' times')
    i += 1
    listener.stop()

This code is mostly a keylogger like the ones found on every tutorial site made for pynput. What I want this to do is run the keylogger in the loop so I can have other code in the loop constantly running (like the counter I have now) but still have keypresses registered. How would I do this?

Also, I'm confused on what listener.join(), with keyboard.Listener(...) as listener:, listener.start() and listener.stop() do. If anyone can help me with explaining anything, I really appreciate it.

🌐
Codeloop
codeloop.org › home › how to automate gui in python with pyautogui
How to Automate GUI in Python with PyAutoGUI - Codeloop
March 20, 2024 - An optional duration integer or float keyword argument specifies the number of seconds it should take to move the mouse to the destination. If you leave it out, the default is 0 for instantaneous movement. (All of the duration keyword arguments in PyAutoGUI functions are optional.)