Python中是否有适用于Mac的sendKey?

时间:2009-11-20 13:04:12

标签: python macos sendkeys

在Mac 10.6中,我希望激活一个活动的应用程序,或者通过Python将其最小化

我知道我可以在Windows中使用带有Python的sendKey,那么在Mac中呢?

5 个答案:

答案 0 :(得分:27)

以下是我从Stack Overflow上的另一个问题中找到的内容。它对我的问题非常有用。

import os
cmd = """
osascript -e 'tell application "System Events" to keystroke "m" using {command down}' 
"""
# minimize active window
os.system(cmd)

答案 1 :(得分:7)

尝试使用PyPI中提供的Apple事件桥appscript

from appscript import app, k
app('System Events').keystroke('N', using=k.command_down)

答案 2 :(得分:4)

除了将按键发送到当前活动应用程序的Yinan之外,您还可以按如下方式将其发送到特定应用程序。像以前一样将以下内容传递给osascript,或将其保存到文件中并将文件传递给osascript

tell application "Safari"
    activate
    tell application "System Events" to keystroke "r" using {command down}
end tell

这会将 Cmd + r 发送到Safari后将其发送到前台

答案 3 :(得分:1)

要使我在SendKeys使用pip的Windows上运行的脚本也适用于OS X,我创建了一个文件/Library/Python/2.7/site-packages/SendKeys/__init__.pysite-packages是{{1}将它安装的所有内容放在我的Mac上......不确定它是否可以配置。)

该文件的内容是:

pip

显然它不是很强大,所以我不会把它放在def SendKeys(keys): if keys == '{ENTER}' keys = 'return' from os import system system('osascript -e \'tell application "System Events" to keystroke ' + keys + "'") 上,但这足以让我的脚本在OS X和Windows上运行。< / p>

答案 4 :(得分:0)

也许您可以从Python运行OSA脚本(man osascript),并驱动应用程序?