macos Python 中是否有适用于 Mac 的 sendKey?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1770312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a sendKey for Mac in Python?
提问by Yinan
In Mac 10.6, I want to cause an active application to become de-active, or minimized by Python
在 Mac 10.6 中,我想让一个活动的应用程序变为非活动状态,或被 Python 最小化
I know I could use sendKey in Windows with Python, then what about in Mac?
我知道我可以在 Windows 中使用 Python 使用 sendKey,那么在 Mac 中呢?
回答by Yinan
Here is what I found from a different question on Stack Overflow. It works pretty good for my problem.
这是我从 Stack Overflow 上的一个不同问题中发现的内容。它对我的问题非常有效。
import os
cmd = """
osascript -e 'tell application "System Events" to keystroke "m" using {command down}'
"""
# minimize active window
os.system(cmd)
回答by Alan Christopher Thomas
回答by Svenito
In addition to Yinan, which will send the keystroke to the currently active application, you can send it to a specific application as follows. Pass the following to osascript as before, or save it to a file and pass the file to osascript
除了 Yinan 会将击键发送到当前活动的应用程序之外,您还可以将其发送到特定应用程序,如下所示。像以前一样将以下内容传递给 osascript,或者将其保存到文件并将文件传递给 osascript
tell application "Safari"
activate
tell application "System Events" to keystroke "r" using {command down}
end tell
This will send Cmd + rto Safari after bringing it to the foreground
将它带到前台后,这会将Cmd + r发送到 Safari
回答by Eric O Lebigot
Maybe you could run an OSA script (man osascript) from Python, for instance, and drive the application?
例如,也许您可以从 Python 运行 OSA 脚本 (man osascript) 并驱动应用程序?
回答by ArtOfWarfare
To make my scripts which already work on Windows using SendKeys
from pip
also work on OS X, I made a file /Library/Python/2.7/site-packages/SendKeys/__init__.py
(site-packages
is where pip
puts everything it installs on my Mac... not sure if that's configurable or not.)
为了使我的脚本,已经使用在Windows上运行SendKeys
的pip
OS X上也工作,我做了一个文件/Library/Python/2.7/site-packages/SendKeys/__init__.py
(site-packages
就是pip
它安装在我的Mac会把所有东西...不知道如果这是配置或没有。)
The contents of the file are:
该文件的内容是:
def SendKeys(keys):
if keys == '{ENTER}'
keys = 'return'
from os import system
system('osascript -e \'tell application "System Events" to keystroke ' + keys + "'")
Obviously it's not very robust, so I won't be putting it on pypi
, but it's enough to make my scripts run on both OS X and Windows.
显然它不是很健壮,所以我不会把它放在pypi
,但它足以让我的脚本在 OS X 和 Windows 上运行。