简体   繁体   English

如何在 Mac 中使用 Python 获得有效的 window 标题?

[英]How to get active window title using Python in Mac?

I am trying to write the Python script which prints the title of the active window using python in Mac OS.我正在尝试编写 Python 脚本,它在 Mac OS 中使用 python 打印活动 window 的标题。

Here is my code:这是我的代码:

from AppKit import NSWorkspace
active_app_name = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName()
print active_app_name

This code just prints name of the app like Google chrome or firefox, but not title.此代码仅打印应用程序的名称,如 Google chrome 或 firefox,但不打印标题。 How to get title of the window?如何获得 window 的标题?

Here is what I used to find both the active application name and window title on Mac OS X using Python by using Quartz API.这是我使用 Quartz API 在 Mac OS X 上使用 Python 查找活动应用程序名称和窗口标题时使用的内容。

First of all, we need to add imports as required:首先,我们需要根据需要添加导入:

if sys.platform == "darwin":
    import applescript
    from AppKit import NSWorkspace
    from Quartz import (
        CGWindowListCopyWindowInfo,
        kCGWindowListOptionOnScreenOnly,
        kCGNullWindowID
    )

And then we can get the active app name and window title via the code below:然后我们可以通过下面的代码获取活动的应用程序名称和窗口标题:

def getActiveInfo(event_window_num):
    try:
        if sys.platform == "darwin":
            app = NSWorkspace.sharedWorkspace().frontmostApplication()
            active_app_name = app.localizedName()

            options = kCGWindowListOptionOnScreenOnly
            windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID)
            windowTitle = 'Unknown'
            for window in windowList:
                windowNumber = window['kCGWindowNumber']
                ownerName = window['kCGWindowOwnerName']
                # geometry = window['kCGWindowBounds']
                windowTitle = window.get('kCGWindowName', u'Unknown')
                if windowTitle and (
                                event_window_num == windowNumber
                        or ownerName == active_app_name
                ):
                    # log.debug(
                    #     'ownerName=%s, windowName=%s, x=%s, y=%s, '
                    #     'width=%s, height=%s'
                    #     % (window['kCGWindowOwnerName'],
                    #        window.get('kCGWindowName', u'Unknown'),
                    #        geometry['X'],
                    #        geometry['Y'],
                    #        geometry['Width'],
                    #        geometry['Height']))
                    break

            return _review_active_info(active_app_name, windowTitle)
        if sys.platform == "win32":
            (active_app_name, windowTitle) = _getActiveInfo_Win32()
            return _review_active_info(active_app_name, windowTitle)
    except:
        log.error('Unexpected error: %s' % sys.exc_info()[0])
        log.error('error line number: %s' % sys.exc_traceback.tb_lineno)
    return 'Unknown', 'Unknown'

There is no access to app title from NSWorkspace.sharedWorkspace().activeApplication() .无法从NSWorkspace.sharedWorkspace().activeApplication()访问应用程序标题。

But you can find the current window title by its PID:但是您可以通过其 PID 找到当前窗口标题:

For example:例如:

from AppKit import NSWorkspace
pid = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationProcessIdentifier']

Then find the right window using below code (it's stored in kCGWindowOwnerPID ) as shown in below code:然后使用下面的代码(它存储在kCGWindowOwnerPID )找到正确的窗口,如下代码所示:

Here is a complete shell example based on @JakeW's script :这是一个基于@JakeW 脚本的完整 shell 示例:

#!/usr/bin/python
# Prints list of windows in the current workspace.
import sys
if sys.platform == "darwin":
    from AppKit import NSWorkspace
    from Quartz import (
        CGWindowListCopyWindowInfo,
        kCGWindowListOptionOnScreenOnly,
        kCGNullWindowID
    )

if sys.platform == "darwin":
    curr_app = NSWorkspace.sharedWorkspace().frontmostApplication()
    curr_pid = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationProcessIdentifier']
    curr_app_name = curr_app.localizedName()
    options = kCGWindowListOptionOnScreenOnly
    windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID)
    for window in windowList:
        pid = window['kCGWindowOwnerPID']
        windowNumber = window['kCGWindowNumber']
        ownerName = window['kCGWindowOwnerName']
        geometry = window['kCGWindowBounds']
        windowTitle = window.get('kCGWindowName', u'Unknown')
        if curr_pid == pid:
            print("%s - %s (PID: %d, WID: %d): %s" % (ownerName, windowTitle.encode('ascii','ignore'), pid, windowNumber, geometry))
elif sys.platform == "win32":
    (active_app_name, windowTitle) = _getActiveInfo_Win32()

It will list details of the current active window including its title.它将列出当前活动窗口的详细信息,包括其标题。

As of macOS 10.6 and later it is better to use: frontmostApplication and if you want to get all of the applications listed you can call runningApplications method.从 macOS 10.6 及更高版本开始,最好使用: frontmostApplication ,如果您想列出所有应用程序,您可以调用runningApplications方法。

You can see more details at https://developer.apple.com/documentation/appkit/nsworkspace#overview您可以在https://developer.apple.com/documentation/appkit/nsworkspace#overview查看更多详细信息

For example:例如:

from AppKit import NSWorkspace
NSWorkspace.sharedWorkspace().runningApplications() // for getting all applications
NSWorkspace.sharedWorkspace().frontmostApplication() // for active window

I tried @kenorb's code but unlucky it can only get the app name, but no title content.我尝试了@kenorb 的代码,但不幸的是它只能获取应用程序名称,但没有标题内容。

I finally found a way to do this with AppleScript: You can find the answer here: MacOSX: get foremost window title我终于找到了使用 AppleScript 执行此操作的方法:您可以在这里找到答案: MacOSX:获得最重要的 window 标题

First create a appleScript GetNameAndTitleOfActiveWindow.scpt首先创建一个appleScript GetNameAndTitleOfActiveWindow.scpt

global frontApp, frontAppName, windowTitle

set windowTitle to ""
tell application "System Events"
    set frontApp to first application process whose frontmost is true
    set frontAppName to name of frontApp
    tell process frontAppName
        tell (1st window whose value of attribute "AXMain" is true)
            set windowTitle to value of attribute "AXTitle"
        end tell
    end tell
end tell

return {frontAppName, windowTitle}

You can test it first in your mac terminal:你可以先在你的mac终端测试一下:

osascript GetNameAndTitleOfActiveWindow.scpt

And then write this in python:然后在python中这样写:

title = subprocess.check_output(['osascript', 'GetNameAndTitleOfActiveWindow.scpt'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM