asweigart / pyautogui

A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.
BSD 3-Clause "New" or "Revised" License
10.22k stars 1.24k forks source link

Memory Leak in 'locateOnScreen' Function During Repeated Calls #806

Open towfikul-islam opened 1 year ago

towfikul-islam commented 1 year ago

When using the locateOnScreen function in a loop to continuously search for an image on the screen, the memory usage of the Python process increases significantly over time.

Steps to Reproduce:

import pyautogui
import time

def find_and_click_button(button_image_path, empty_checkbox_image_path, checked_checkbox_image_path, accuracy_wanted, boxes_to_click):
    click_count = 0
    button_location = ''

    while True:
        # Locate the button on the screen
        button_location = pyautogui.locateOnScreen('button.png', confidence=accuracy_wanted)

        if button_location:
            # click the checkboxes
            click_checkboxes(empty_checkbox_image_path, checked_checkbox_image_path, boxes_to_click, accuracy_wanted)

            # Get the center of the button
            button_center = pyautogui.center(button_location)

            # Click the button
            pyautogui.click(button_center)

            # Remove previous logs
            os.system('cls')

            # Show log of clicking event
            click_count += 1
            print('Total trades: ', click_count)

            # Sleep for a short duration before searching again
            time.sleep(3)
        else:
            # If button is not found, wait for a short duration before trying again
            time.sleep(3)

Expected Behavior: The memory usage should remain relatively constant over time, given that the same operation is being performed in each iteration of the loop.

Actual Behavior: The memory usage increases significantly over time. In my tests, I observed an average increase of approximately 6MB every 5 seconds.

This is what is I see using psutil: image

Using memory profiler I could figure out that the 'locateOnScreen' function has an increment, which should be zero:
image

Environment: Python Version: 3.10.6 pyautogui Version: 0.9.53 Operating System: Windows-10-10.0.22621-SP0

Additional Information: