Calling AppleScript from Python without using osascript or appscript?

微笑、不失礼 提交于 2019-12-31 08:38:09

问题


Is there any way to execute (and obtain the results of) AppleScript code from python without using the osascript command-line utility or appscript (which I don't really want to use (I think?) because it's no longer developed/supported/recommended)?

Rationale: in another question I've just posted, I describe a strange/undesired behaviour I'm experiencing with running some AppleScript via osascript. As I'm actually calling it from a python script, I wondered if there was a way to route around osascript altogether, since that seems to be where the problem lies - but appscript (the obvious choice?) looks risky now...


回答1:


You can use the PyObjC bridge:

>>> from Foundation import *
>>> s = NSAppleScript.alloc().initWithSource_("tell app \"Finder\" to activate")
>>> s.executeAndReturnError_(None)



回答2:


PyPI is your friend...

http://pypi.python.org/pypi/py-applescript

Example:

import applescript

scpt = applescript.AppleScript('''
    on run {arg1, arg2}
        say arg1 & " " & arg2
    end run

    on foo()
        return "bar"
    end foo

    on Baz(x, y)
        return x * y
    end bar
''')

print(scpt.run('Hello', 'World')) #-> None
print(scpt.call('foo')) #-> "bar"
print(scpt.call('Baz', 3, 5)) #-> 15


来源:https://stackoverflow.com/questions/16065162/calling-applescript-from-python-without-using-osascript-or-appscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!