macos 如何在 Python 脚本中嵌入 AppleScript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2940916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:58:17  来源:igfitidea点击:

How do I embed an AppleScript in a Python script?

pythonmacosapplescript

提问by dbmikus

I am trying to embed an AppleScript in a Python script. I don't want to have to save the AppleScript as a file and then load it in my Python script. Is there a way to enter the AppleScript as a string in Python and have Python execute the AppleScript? Thanks a bunch.

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

Here is my script: import subprocess import re import os

这是我的脚本: 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()

回答by has

Use 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)

回答by Alex Martelli

Example 3 in this articlesuggests:

本文中的示例 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()

These days, however, subsystem.Popenis usually preferred over os.system(the article is from three years ago, when nobody screamed on seeing an os.systemcall;-).

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

回答by gbonetti

In python 3 it would be slightly different:

在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 now expects a byte-like object, to pass a string, the universal_newlines=Trueparameter is needed.

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

回答by Antal Spector-Zabusky

Rather than embedding AppleScript, I would instead use appscript. I've never used the Python version, but it was very nice in Ruby. And make sure that, if you're installing it on Snow Leopard, you have the latest version of XCode.However, I've so far been unable to install it on Snow Leopard. But I've only had Snow Leopard for ~1 day, so your mileage may vary.

我不会嵌入 AppleScript,而是使用appscript。我从未使用过 Python 版本,但它在 Ruby 中非常好。 并确保,如果您在 Snow Leopard 上安装它,您拥有最新版本的 XCode。但是,到目前为止,我一直无法在 Snow Leopard 上安装它。但我只吃雪豹大约 1 天,所以你的里程可能会有所不同。

回答by firesofmay

Here's a generic function in python. Just pass your applescript code with/without args and get back the value as a string. Thanks to thisanswer.

这是python中的一个通用函数。只需使用/不使用 args 传递您的 Applescript 代码,然后将值作为字符串返回。感谢这个答案。

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'])

回答by firesofmay

You can use os.system:

您可以使用os.system

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

or, as suggested by Alex Martelli you can use a variable:

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

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

回答by Mark Chackerian

Here's a simple python3 synchronous example, if you want your python code not to wait for Applescript to finish. In this example, both saycommands are executed in parallel.

这是一个简单的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')