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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:33:37  来源:igfitidea点击:

Is there a sendKey for Mac in Python?

pythonmacossendkeys

提问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

Try appscript, an Apple event bridge available in PyPI:

试试appscript,这是 PyPI 中可用的 Apple 事件桥:

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

回答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 SendKeysfrom pipalso work on OS X, I made a file /Library/Python/2.7/site-packages/SendKeys/__init__.py(site-packagesis where pipputs everything it installs on my Mac... not sure if that's configurable or not.)

为了使我的脚本,已经使用在Windows上运行SendKeyspipOS X上也工作,我做了一个文件/Library/Python/2.7/site-packages/SendKeys/__init__.pysite-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 上运行。