从 Python 脚本获取 macOS 上所有 window 标题的列表

Obtain list of all window titles on macOS from a Python script

我希望能够从 Python 脚本获取 macOS 上所有 window 标题的字符串列表。在 Windows 上,有一个 win32 api(enumWindows() 函数)可以做到这一点;我想要 macOS 等效版本。

这可能吗?我假设我需要使用 pyobjc。

以下脚本基于 Mark Setchell 的评论并打印应用程序名称和 window 名称(使用 Python 3.7):

import Quartz

windows = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements|Quartz.kCGWindowListOptionOnScreenOnly,Quartz.kCGNullWindowID);

for window in windows:
    print(f"{window[Quartz.kCGWindowOwnerName]}: {window.get(Quartz.kCGWindowName, '<no name>')}")

请注意,windows 可能没有名称,因此使用 "get" 方法访问 window 名称。