MacOS下Python调用screencapture报错‘could not create image from window’求助
问题描述
环境
- macOS 12.6.8
- Apple Silicon
- Python 3.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
问题:直接在终端执行screencapture -x -l 3087 test.png可正常截图,但通过Python调用时出现上述错误,寻求解决方法。
解决办法
核心问题是单引号包裹的字符串无法解析Python变量占位符,{windowId}在os.system调用中只是被当作普通字符串传递,没有替换成实际的窗口ID数值。
修复方式1:使用f-string格式化命令
将命令字符串改为f-string格式,让Python自动替换变量:
os.system(f'screencapture -x -l {windowId} test.png')
修复方式2:使用字符串格式化方法
如果兼容低版本Python,可改用str.format():
os.system('screencapture -x -l {} test.png'.format(windowId))
额外建议:改用subprocess模块(更推荐)
os.system属于较旧的API,subprocess.run()更安全且功能更完善,示例如下:
import subprocess # 注意将windowId转为字符串,因为参数列表要求每个元素都是字符串类型 subprocess.run(['screencapture', '-x', '-l', str(windowId), 'test.png'], check=True)
内容的提问来源于stack exchange,提问作者itmeng
相关产品推荐
相关产品推荐

