【问题标题】:Which Python module ,libraries are available for OSX Automation? [duplicate]哪些 Python 模块、库可用于 OSX 自动化? [复制]
【发布时间】:2018-03-12 05:27:42
【问题描述】:

我正在寻找任何用于 OSX 自动化的模块,例如通过 Python 打开任何应用程序并通过 Python 控制鼠标、键盘等。我尝试使用 AppleScript,但我想知道我是否可以访问鼠标、键盘并可以使用 OSX 上的任何应用程序自动化Python?我找到了pyauto,如果有其他好的 Python 库,OSX 自动化模块请告诉我。

【问题讨论】:

  • ATOMac / pyatom 是目前 Python 中唯一的一个。它仅适用于 Python2.7,但足以获取文本等。

标签: python macos python-3.x automation automated-tests


【解决方案1】:

我也在寻找一个好的 python 模块来在 python 中使用“applescript”。事实上,我就是这样来到这里的。我找不到任何东西,所以我不得不想出自己的解决方案。

最适合我的是使用 subprocess 模块从我的 python 程序中调用 osascript。

更准确地说,(请参阅下面的代码以获取示例),如果我想在我的日历中添加一些内容,我会在我的 python 程序中生成将其作为字符串执行的 applescript,然后将其通过管道传输到 osascript。

这不是超级优雅,也可能不是超级快,但效果很好。因此,我目前正在编写一个日历模块,该模块具有用于添加事件、获取事件列表的 python 函数......并且每个都将 applescript 生成为字符串并调用 osascript。

这听起来很糟糕,但效果很好,一旦你有一个你最喜欢的程序的模块,你就不需要再担心 applescript。

需要一种方法在 applescript 中对返回数据进行编码,然后在 python 程序中对其进行解码。对我来说,传入和传出 applescript 的大多数数据都是类似字典的,到目前为止,使用 re 模块这还不是问题。

这是获取日历“生日”的 uid 的示例。

我的方法的主要问题是我需要为我想在 applescript 中访问的所有内容编写包装函数。一个令人厌烦的过程。

我看到的主要优势是 a) 它有效,我可以到达我想要的地方,b) 它似乎是未来的证明。因为,如果苹果在某个时候放弃了 applescript 以支持 javascript 或其他什么,那么一旦我调整了包装模块,我的所有程序仍然可以工作。

不管怎样……

希望对您有所帮助。

顺便说一句,如果有人知道更好的方法,请告诉我。或者如果有人不知道更好的方法但喜欢我的方法并且有兴趣帮助编写包装模块,也请告诉我。

这是一个例子。

最好, 斯蒂芬

import subprocess

def asrun(ascript):
  "Run the AppleScript ascript and return the standard output and error."
  return subprocess.run(['osascript'],
                         input=ascript,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         encoding="utf-8")


def get_uid_of_calendar(name):
    script = '''\
    tell application "Calendar"
         return uid of calendar "'''+name+'''"
    end tell
    '''
    cal_res = asrun(script)
    return cal_res.stdout

get_uid_of_calendar("Birthdays")

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 2015-04-15
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多