如何在Python脚本中嵌入AppleScript?

dbm*_*kus 11 python macos applescript

我试图在Apple脚本中嵌入AppleScript.我不想将AppleScript保存为文件,然后将其加载到我的Python脚本中.有没有办法在Apple中将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()
Run Code Online (Sandbox Code Playgroud)

has*_*has 22

使用子进程:

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)
Run Code Online (Sandbox Code Playgroud)

  • 在 python 3 中这是行不通的,需要在 popen 上添加一个额外的参数 Universal_newlines=True 。请参阅下面的示例 /sf/answers/3159374851/ (3认同)

Ale*_*lli 5

本文中的示例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()
Run Code Online (Sandbox Code Playgroud)

然而,这些日子subsystem.Popen通常比较优先os.system(文章来自三年前,当没有人看到os.system电话时尖叫;-).


gbo*_*tti 5

在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)
Run Code Online (Sandbox Code Playgroud)

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