如何在Python脚本中嵌入AppleScript?

时间:2010-05-31 01:08:24

标签: python macos applescript

我正在尝试在Apple脚本中嵌入AppleScript。我不想将AppleScript保存为文件,然后将其加载到我的Python脚本中。有没有办法在Apple中将AppleScript作为字符串输入并让Python执行AppleScript?非常感谢。

这是我的脚本:     导入子流程     进口重新     import os

def get_window_title():
    cmd = """osascript<<END
    tell application "System Events"
        set frontApp to name of first application process whose frontmost is true
    end tell
    tell application frontApp
        if the (count of windows) is not 0 then
            set window_name to name of front window
        end if
    end tell
    return window_name
    END"""

    p = subprocess.Popen(cmd, shell=True)
    p.terminate()
    return p

def get_class_name(input_str):
    re_expression = re.compile(r"(\w+)\.java")
    full_match = re_expression.search(input_str)
    class_name = full_match.group(1)
    return class_name

print get_window_title()

9 个答案:

答案 0 :(得分:21)

使用subprocess

from subprocess import Popen, PIPE

scpt = '''
    on run {x, y}
        return x + y
    end run'''
args = ['2', '2']

p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
print (p.returncode, stdout, stderr)

答案 1 :(得分:5)

this article中的示例3建议:

#!/usr/bin/env python
#sleepy-mac.py
#makes my mac very sleepy

import os
cmd = """osascript -e 'tell app "Finder" to sleep'"""
def stupidtrick():
     os.system(cmd)
stupidtrick()

但是,这些天subsystem.Popen通常比os.system更受欢迎(该文章来自三年前,当时没有人在看到os.system电话时尖叫; - )。

答案 2 :(得分:4)

在python 3中,它会略有不同:

script = 'tell "some application" to do something'
p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
stdout, stderr = p.communicate(script)

Popen现在需要一个类似字节的对象来传递一个字符串,需要universal_newlines=True参数。

答案 3 :(得分:1)

我会使用appscript而不是嵌入AppleScript。我从未使用过Python版本,但它在Ruby中非常好用。 And make sure that, if you're installing it on Snow Leopard, you have the latest version of XCode. 但是,我到目前为止还无法在Snow Leopard上安装它。但我只有雪豹约1天,所以你的里程可能会有所不同。

答案 4 :(得分:1)

subprocess.run()now preferred 超过 subprocess.popen()。这是运行 AppleScript 代码并返回结果的非常简单的方法。

import subprocess

def get_window_title():
    cmd = """
        tell application "System Events"
            set frontApp to name of first application process whose frontmost is true
        end tell
        tell application frontApp
            if the (count of windows) is not 0 then
                set window_name to name of front window
            end if
        end tell
        return window_name
    """
    result = subprocess.run(['osascript', '-e', cmd], capture_output=True)
    return result.stdout

print(get_window_title())

答案 5 :(得分:0)

这是python中的通用函数。只需传递带有/不带args的applescript代码,然后将值作为字符串返回。感谢this回答。

from subprocess import Popen, PIPE

def run_this_scpt(scpt, args=[]):
    p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate(scpt)
    return stdout

#Example of how to run it.
run_this_scpt("""tell application "System Events" to keystroke "m" using {command down}""")

#Example of how to run with args.
run_this_scpt('''
    on run {x, y}
        return x + y
    end run''', ['2', '2'])

答案 6 :(得分:0)

您可以使用os.system

import os
os.system('''
    osascript -e 
     '[{YOUR SCRIPT}]'
     '[{GOES HERE}]'
    ''')

或者,正如Alex Martelli所建议的那样,您可以使用变量:

import os
script = '''
    [{YOUR SCRIPT}]
    [{GOES HERE}]
'''
os.system('osascript -e ' + script)

答案 7 :(得分:0)

这是一个简单的python3同步示例,如果您希望您的python代码不等待Applescript完成。在此示例中,两个say命令并行执行。

from subprocess import Popen

def exec_applescript(script):
    p = Popen(['osascript', '-e', script])

exec_applescript('say "I am singing la la la la" using "Alex" speaking rate 140 pitch 60')
exec_applescript('say "Still singing, hahaha" using "Alex" speaking rate 140 pitch 66')

答案 8 :(得分:0)

请参见https://pypi.org/project/applescript/

import applescript
resp = applescript.tell.app("System Events",'''
set frontApp to name of first application process whose frontmost is true
return "Done"
''')
assert resp.code == 0, resp.err
print(resp.out)

等 大部分建议(包括我引用的“ applescript”)都缺少osascript的一项重要设置-将-s选项设置为“ s”,否则您将难以解析输出。