如何在 Python 脚本中嵌入 AppleScript?

发布于 2024-09-03 17:08:03 字数 885 浏览 6 评论 0原文

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

这是我的脚本: 导入子流程 进口重新 导入操作系统

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

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.

Here is my script:
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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

那一片橙海, 2024-09-10 17:08:03

使用子进程

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)

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)
桃扇骨 2024-09-10 17:08:03

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

In python 3 it would be slightly different:

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=True parameter is needed.

可是我不能没有你 2024-09-10 17:08:03

这篇文章 建议:

#!/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 调用时尖叫;-)。

Example 3 in this article suggests:

#!/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.Popen is usually preferred over os.system (the article is from three years ago, when nobody screamed on seeing an os.system call;-).

善良天后 2024-09-10 17:08:03

如果您希望您的 python 代码不等待 Applescript 完成,这里有一个简单的 python3 同步示例。在此示例中,两个 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')

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

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')
叹梦 2024-09-10 17:08:03

subprocess.run()现在优先优于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())

subprocess.run() is now preferred over subprocess.popen(). Here is a pretty simple way to run AppleScript code and get the results back.

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())
或十年 2024-09-10 17:08:03

请参阅 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”,否则您将难以解析输出。

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

etc.
Most of suggestions, including "applescript" I quoted, are missing one important setting to osascript -- setting an -s option to "s", otherwise you will be having difficulty parsing the output.

随心而道 2024-09-10 17:08:03

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

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.

ζ澈沫 2024-09-10 17:08:03

您可以使用 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)

You can use os.system:

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

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

import os
script = '''
    [{YOUR SCRIPT}]
    [{GOES HERE}]
'''
os.system('osascript -e ' + script)
吹泡泡o 2024-09-10 17:08:03

这是 python 中的通用函数。只需传递带/不带参数的 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'])

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 this answer.

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'])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文