pyobjc icon indicating copy to clipboard operation
pyobjc copied to clipboard

Completion handlers hang when running multiple instances

Open torablien opened this issue 1 year ago • 1 comments

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

torablien avatar Sep 08 '24 16:09 torablien

As per https://chromium.googlesource.com/chromium/src/+/lkgr/ui/snapshot/snapshot_mac.mm#155, this was macOS bug and has been resolved

xhruso00 avatar Oct 18 '25 13:10 xhruso00