macOS 12.6.8 苹果硅 python3.9.6
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')
3087
could not create image from window
在终端可以直接使用命令,但在Python上不行
您的
os.system()
调用正在运行带有文字 {windowID}
字符串的命令。您的意思是使用 f 字符串吗?那就是:os.system(f'screencapture -x -l {windowId} test.png')
?除此之外,我会注意到您永远不应该使用 os.system()
,因为您传递给它的字符串是由 shell 解释的。这总是有风险的,因为如果任何插值包含 shell 元字符(例如 {
和 }
),它不会执行您期望的操作,并且可能会产生不需要的副作用。