ronaldoussoren / pyobjc

The Python <-> Objective-C Bridge with bindings for macOS frameworks
https://pyobjc.readthedocs.io
563 stars 47 forks source link

Completion handlers hang when running multiple instances #622

Open torablien opened 2 months ago

torablien commented 2 months ago

I am using ScreenCaptureKit to capture screenshots and when I run two or more instances of the python script in parallel, the capture process silently hangs until I close all but one.

Simplified example that captures a screenshot every 2s:

import logging
import time

from AppKit import NSBitmapImageFileTypePNG, NSBitmapImageRep
from ScreenCaptureKit import (
    SCContentFilter,
    SCScreenshotManager,
    SCShareableContent,
    SCStreamConfiguration,
)

def capture_screenshot(save_path: str):
    def shareable_content_completion_handler(shareable_content, error):
        content_filter = SCContentFilter.alloc().initWithDisplay_excludingApplications_exceptingWindows_(
            shareable_content.displays()[0], [], []
        )
        configuration = SCStreamConfiguration.alloc().init()
        SCScreenshotManager.captureImageWithFilter_configuration_completionHandler_(
            content_filter, configuration, capture_image_completion_handler
        )

    def capture_image_completion_handler(image, error):
        bitmap_rep = NSBitmapImageRep.alloc().initWithCGImage_(image)
        png_data = bitmap_rep.representationUsingType_properties_(
            NSBitmapImageFileTypePNG, None
        )
        png_data.writeToFile_atomically_(save_path, True)
        logging.info(f"Screenshot saved at {save_path}")

    SCShareableContent.getShareableContentWithCompletionHandler_(
        shareable_content_completion_handler
    )

    time.sleep(1)  # use a threading.event here but it's not necessary for this example

def main():
    logging.basicConfig(level=logging.DEBUG)
    while True:
        curr_time_s = time.strftime("%Y-%m-%d_%H-%M-%S")
        capture_screenshot(save_path=f"screenshot_{curr_time_s}.png")
        time.sleep(2)

If this is the only python script doing this, it works fine. If you run another instance of it in parallel (i.e. multiple apps open), both hang silently until you close all but one. Any ideas why and/or direction to take to debug/workaround? Thanks!

Running Python 3.12 on M1 Pro 14.5