macos python os screencapture : 'could not create image from window'

47 Views Asked by At

env

macos 12.6.8 Apple Silicon python3.9.6

code

import os
from Quartz import CGWindowListCopyWindowInfo, kCGNullWindowID, kCGWindowListOptionAll


windowName = 'Code'

windowList = CGWindowListCopyWindowInfo(
        kCGWindowListOptionAll, kCGNullWindowID)

for window in windowList:
    if window["kCGWindowOwnerName"] == windowName and window["kCGWindowBounds"]["X"] > 0:
        windowId = window['kCGWindowNumber']
        print(windowId)
        os.system('screencapture -x -l {windowId} test.png')

output:

3087
could not create image from window

Directly using commands is available at the terminal, but not on Python

1

There are 1 best solutions below

0
Kurtis Rader On

Your os.system() call is running a command with a literal {windowID} string. Did you mean to use an f-string? That is: os.system(f'screencapture -x -l {windowId} test.png')? Beyond that observation I'll note that you should never use os.system() because the string you pass to it is interpreted by a shell. Which is always risky because if any of the interpolated values contain shell meta-characters (such as { and }) it won't do what you expect and could have unwanted side-effects.