So I was making a python script that clicked a spot on my screen, using AI to get positions. Simple as that. However I got a error saying I used ALL of my memory. I realize that when I left the script on it used about a gigabyte every 10 seconds.
Here is my code:
import pyautogui
import cv2
import numpy as np
import time
import gc
import sys
sys.setrecursionlimit(999999999)
num = 1
def take_screenshot():
screenshot = pyautogui.screenshot()
screenshot = np.array(screenshot)
return cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
def find_and_click_text():
template_image = "C:/Users/Owner/template2.png"
screenshot = take_screenshot()
template = cv2.imread(template_image, cv2.IMREAD_COLOR)
h, w = template.shape[:-1]
result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
if max_val > 0.8: # Adjust this threshold based on your needs
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
pyautogui.keyDown('fn')
pyautogui.keyDown('f12')
pyautogui.moveTo((top_left[0] + w/2, top_left[1] + h/2))
pyautogui.mouseDown()
pyautogui.click()
skip()
else:
global num
num += 1
if num >= 10:
skip()
num = 0
else:
find_and_click_text()
def skip():
skipurl = "C:/Users/Owner/skip2.png"
screenshot2 = take_screenshot()
template2 = cv2.imread(skipurl, cv2.IMREAD_COLOR)
h, w = template2.shape[:-1]
result2 = cv2.matchTemplate(screenshot2, template2, cv2.TM_CCOEFF_NORMED)
min_val, max_val2, min_loc, max_loc2 = cv2.minMaxLoc(result2)
if max_val2 > 0.8:
top_left2 = max_loc2
bottom_right2 = (top_left2[0] + w, top_left2[1] + h)
pyautogui.keyDown('fn')
pyautogui.keyDown('f8')
pyautogui.moveTo((top_left2[0] + w/2, top_left2[1] + h/2))
pyautogui.mouseDown()
pyautogui.click()
time.sleep(0.5)
find_and_click_text()
else:
global num
num += 1
if num >= 10:
find_and_click_text()
num = 0
else:
skip()
find_and_click_text()
I'm new to Python (like literally today new), but I am experienced in web development, so I got the jist. I was wondering if this was a optimisation problem or I'm just really dumb?
Edit: So I think my solution is just to stop the script every 3 minutes 15 seconds (I timed it, it takes around 8gbs memory) and start it again. It releases the memory and I can keep going. This isnt easy though because the whole point is that it is automated. How would I be able to stop the script wait like 5 or 10 seconds and start it again? Maybe this would be like time.sleep or something. Im very new to Python
It looks like you don't have a escape clause. You are using recursion in any possible case. When does your program ends? In addition, setting 999,999,999 is excessive.