How to get active window title using Python in Mac?

前端 未结 2 1295
傲寒
傲寒 2020-12-31 17:28

I am trying to write the Python script which prints the title of the active window using python in Mac OS.

Here is my code:

from AppKit import NSWork         


        
2条回答
  •  有刺的猬
    2020-12-31 17:52

    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.

    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'
    

提交回复
热议问题