如何在Python脚本中嵌入AppleScript?

19 投票
9 回答
29181 浏览
提问于 2025-04-15 23:21

我想把一个AppleScript嵌入到我的Python脚本里。我不想先把AppleScript保存成文件,然后再在Python脚本中加载它。有没有办法直接在Python中把AppleScript写成字符串,然后让Python执行这个AppleScript呢?非常感谢!

这是我的脚本:

import subprocess

import re

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 个回答

6

这篇文章的例子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调用时,没人会大喊大叫;-)。

9

在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这个参数。

26

使用 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)

撰写回答