使用 Python 在 Mac OS X 中查找当前活动窗口 [英] Finding the Current Active Window in Mac OS X using Python

查看:31
本文介绍了使用 Python 在 Mac OS X 中查找当前活动窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Mac OS X 上使用 Python 找到给定时间当前活动窗口的应用程序名称?

Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?

推荐答案

这应该有效:

#!/usr/bin/python

from AppKit import NSWorkspace
activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']
print activeAppName

仅适用于 Leopard 或 Tiger,前提是您安装了 PyObjC 并且碰巧在第一行指向了正确的 Python 二进制文件(如果您安装了通用 MacPython,则情况并非如此,您可能想在 Tiger 上这样做)).但是 Peter 用 Carbon 的方式来回答可能会快很多,因为在 Python 中从 AppKit 导入任何东西需要一段时间,或者更准确地说,在 Python 进程中第一次从 AppKit 导入东西需要一段时间.

Only works on Leopard, or on Tiger if you have PyObjC installed and happen to point at the right python binary in line one (not the case if you've installed universal MacPython, which you'd probably want to do on Tiger). But Peter's answer with the Carbon way of doing this will probably be quite a bit faster, since importing anything from AppKit in Python takes a while, or more accurately, importing something from AppKit for the first time in a Python process takes a while.

如果您需要在 PyObjC 应用程序中使用它,我所描述的将工作得很好而且很快,因为您只会遇到导入 AppKit 一次的延迟.如果您需要将其用作命令行工具,您会注意到性能下降.如果这与您相关,那么您最好使用 Peter 的代码作为起点,在 Xcode 中构建一个 10 行 Foundation 命令行工具.

If you need this inside a PyObjC app, what I describe will work great and fast, since you only experience the lag of importing AppKit once. If you need this to work as a command-line tool, you'll notice the performance hit. If that's relevant to you, you're probably better off building a 10 line Foundation command line tool in Xcode using Peter's code as a starting point.

这篇关于使用 Python 在 Mac OS X 中查找当前活动窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆