如何在Python脚本中嵌入AppleScript ?

时间:2022-05-27 07:09:06

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

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

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

7 个解决方案

#1


20  

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)

#2


5  

Example 3 in this article suggests:

本文中的示例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.Popen is usually preferred over os.system (the article is from three years ago, when nobody screamed on seeing an os.system call;-).

然而,这些天子系统。Popen通常比os更受欢迎。系统(这篇文章是三年前写的,当时没人看到操作系统就尖叫。系统调用;-)。

#3


4  

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

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

#4


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.

我宁愿使用appscript而不是嵌入AppleScript。我从来没有使用过Python版本,但是在Ruby中非常好。请确保,如果您在雪豹上安装它,您将拥有最新版本的XCode。但是,到目前为止,我还无法将它安装到Snow Leopard中。但是我只吃了1天雪豹,所以你的里数可能会不一样。

#5


0  

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)

#6


0  

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.

这是python中的一个通用函数。只需将您的applescript代码与args一起传递,并将其作为字符串返回。多亏了这个答案。

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

#7


0  

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.

这里有一个简单的python3同步示例,如果您希望您的python代码不要等待Applescript完成的话。在本例中,两者都说命令是并行执行的。

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

#1


20  

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)

#2


5  

Example 3 in this article suggests:

本文中的示例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.Popen is usually preferred over os.system (the article is from three years ago, when nobody screamed on seeing an os.system call;-).

然而,这些天子系统。Popen通常比os更受欢迎。系统(这篇文章是三年前写的,当时没人看到操作系统就尖叫。系统调用;-)。

#3


4  

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

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

#4


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.

我宁愿使用appscript而不是嵌入AppleScript。我从来没有使用过Python版本,但是在Ruby中非常好。请确保,如果您在雪豹上安装它,您将拥有最新版本的XCode。但是,到目前为止,我还无法将它安装到Snow Leopard中。但是我只吃了1天雪豹,所以你的里数可能会不一样。

#5


0  

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)

#6


0  

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.

这是python中的一个通用函数。只需将您的applescript代码与args一起传递,并将其作为字符串返回。多亏了这个答案。

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

#7


0  

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.

这里有一个简单的python3同步示例,如果您希望您的python代码不要等待Applescript完成的话。在本例中,两者都说命令是并行执行的。

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