macos python os screencapture:“无法从窗口创建图像”

问题描述 投票:0回答:1

环境

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上不行

python macos screenshot
1个回答
0
投票

您的

os.system()
调用正在运行带有文字
{windowID}
字符串的命令。您的意思是使用 f 字符串吗?那就是:
os.system(f'screencapture -x -l {windowId} test.png')
?除此之外,我会注意到您永远不应该使用
os.system()
,因为您传递给它的字符串是由 shell 解释的。这总是有风险的,因为如果任何插值包含 shell 元字符(例如
{
}
),它不会执行您期望的操作,并且可能会产生不需要的副作用。

© www.soinside.com 2019 - 2024. All rights reserved.