spyoungtech / ahk

Python wrapper for AutoHotkey with full type support. Harness the automation power of AutoHotkey with the beauty of Python.
MIT License
887 stars 66 forks source link

Memory leak when calling run_script #338

Closed Apprisco closed 2 months ago

Apprisco commented 2 months ago

describe your issue

Had a python based AHK script running that consistently presses some values using asyncahk. Memory kept increasing over time, currently over 4GB.``

ahk.version

latest

AutoHotkey version

v1

Code to reproduce the issue

from ahk import AHK,AsyncAHK

class Trove:
    ahk=AHK(directives=[NoTrayIcon])
    asyncAHK=AHK(directives=[NoTrayIcon])

while True:
    script='''.......'''
    ahk.run_script(script)
    asyncAHK.run_script(script)

Traceback/Error message

Observe memory usage increasing over time.

spyoungtech commented 2 months ago

Thanks for the report. I confirmed this behavior is reproducible with run_script and calls with blocking=False. It's likely related to resources for the subprocess.

spyoungtech commented 2 months ago

I believe I found the cause of this.

The creation of AutoHotkey processes uses the start method (or here in the sync API), which includes a call to atexit.register, which is an attempt to ensure that the subprocess will be cleaned up when the Python script is finished -- to avoid leaving AutoHotkey running after Python is done executing.

However, this obviously causes a reference to be held for the subprocess.Popen object, so it never gets garbage collected.

When I remove this line, the memory buildup no longer occurs.

Apprisco commented 2 months ago

How am I able to copy your fix? Will there be an updated version of AHK wrapper released soon? Thanks :) This library is genuinely awesome for people who want to use AHK but not in a synchronous loop, and it's pretty damn great asides from the memory leak lol.

While I understand this is an open source project and i cannot expect a fast response, a memory leak is a pretty critical issue to deal with.

spyoungtech commented 2 months ago

@Apprisco I've opened #339 with a fix for this issue. As long as tests pass, it should be released within the next day, if not the next hour or so.

spyoungtech commented 2 months ago

This is fixed in version 1.8.0

Apprisco commented 2 months ago

Hell yeah, thanks man!