使用 Python 代替 AppleScript

Using Python in Place of AppleScript

我经常使用 Applescript 来完成基本任务,例如打开和关闭程序,有时会更深入一些,例如 运行 特定 Xcode 程序的单元测试。我正在学习 Python,我喜欢它。我没能找到很多关于 AppleScript 和 Python 的文档。我的问题是:在 Mac OS X 上,可以使用 Python 代替 AppleScript 来完成上述任务吗?如果是这样,有没有人知道可以更好地了解该主题的资源?

Python 不能用于替代 AppleScript 提供的 UI 和自动化任务。然而,由于 OS X 10.10 (Yosemite) JavaScript 也可以使用。

看这里:https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/index.html

不能真正取代它,但有一个可用的包装器:https://pypi.python.org/pypi/py-applescript/1.0.0...所以您可以在您的 python 程序中与它交互。

使用 Cocoa 您可以直接使用 AESendMessage 发送事件。不过还有很多工作要做。这是一个提供示例的要点:

https://gist.github.com/pudquick/9683c333e73a82379b8e377eb2e6fc41

为了避免所有过时的和所谓的 "crappy" 模块,包括 PyObjC,可以简单地在脚本编辑器或脚本调试器(我的选择)中调试脚本,然后通过 Popen 使用 osascript 执行它.我更喜欢这个,这样我可以确保应用程序实现的特性得到解决,并且 Script Debugger 具有出色的调试和浏览工具。

例如:

from subprocess import Popen, PIPE

def get_front_win_id():
    """
    Get window id of front Chrome browser window
    """
    script = '''
        on run {}
            set winID to 0
            tell application "Google Chrome"
                set winID to id of front window
                return winID
            end tell
        end run
    '''
    args = []
    p = Popen(['/usr/bin/osascript', '-'] + args,
              stdin=PIPE, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate(script)
    winID = stdout.strip()
    return int(winID)

将列表中的 args 传递给 osascript,但它们必须是字符串,因此复杂的数据结构编组和解组可能很乏味,但简单是有代价的。为了简单起见,我放弃了错误检查和异常 handling/raising。坦斯塔夫

虽然您可以生成复杂的 python 调用与 AppleScript 相同的 Apple 事件,但有些事情在 AppleScript 中处理起来更容易。

不过在 python 中执行一些 AS 很容易:

from Foundation import NSAppleScript
textOfMyScript = """
   *(Your AppleScript Here)*
"""
myScript = NSAppleScript.initWithSource_(NSAppleScript.alloc(), textOfMyScript)
results, err = myScript.executeAndReturnError_(None)

结果是一个NSAppleEventDescriptor,如果你需要把数据取出来。