如何在Python脚本中嵌入AppleScript?
我正在尝试在Python脚本中嵌入AppleScript。我不想将AppleScript保存为文件,然后将其加载到Python脚本中。有没有办法在Python中以字符串形式输入AppleScript并让Python执行AppleScript?非常感谢 这是我的剧本: 导入子流程 进口稀土 导入操作系统如何在Python脚本中嵌入AppleScript?,python,macos,applescript,Python,Macos,Applescript,我正在尝试在Python脚本中嵌入AppleScript。我不想将AppleScript保存为文件,然后将其加载到Python脚本中。有没有办法在Python中以字符串形式输入AppleScript并让Python执行AppleScript?非常感谢 这是我的剧本: 导入子流程 进口稀土 导入操作系统 def get_window_title(): cmd = """osascript<<END tell application "System Events"
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()
def get_window_title():
cmd=“”osascript中的示例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
呼叫时尖叫;-)
这是python中的一个通用函数。只需传递带/不带参数的applescript代码,然后以字符串形式返回值。感谢您的回答
您可以使用操作系统
:
import os
os.system('''
osascript -e
'[{YOUR SCRIPT}]'
'[{GOES HERE}]'
''')
或者,根据Alex Martelli的建议,您可以使用一个变量:
import os
script = '''
[{YOUR SCRIPT}]
[{GOES HERE}]
'''
os.system('osascript -e ' + script)
在Python3中,情况会略有不同:
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\u newlines=True
参数。这里有一个简单的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')
看
等等。
大多数建议,包括我引用的“applescript”,都缺少osascript的一个重要设置—将-s选项设置为“s”,否则您将很难解析输出。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())
我以前查看过该链接,但我的脚本无法正常运行。我编辑了我的问题,以包含我正在尝试执行的脚本。我认为错误在于我无法从AppleScript检索返回值。我查看了Popen对象,但找不到任何可对返回值进行操作的内容。很抱歉,听到您有问题;它应该可以工作(在这里可以)。你试过在rb appscript讨论()上发布吗需要帮助吗?哈斯:谢谢你的链接,但我只是在1.5天前安装了雪豹,今天我花了很多时间旅行;我还没有真正尝试过。不过,如果我不能让它工作,我会检查一下;再次感谢。哈斯:事实上,我所需要做的就是。再次感谢你!很高兴你把它整理好了。是的,如果OP不介意第三方的话安装后,py appscript是一个更好的解决方案。例如,这将获取最前面进程中所有窗口的名称:
app('System Events')。应用程序处理[its.frontmost==True]。first.windows.name()
仅供参考,PyPI上有一个小python模块可以实现这一点:在python 3中,这不起作用,需要在popen上增加一个参数universal_newlines=True。请参见下面的示例@gbonetti,这不一定是真的。在python 3中,如果脚本文本包含非ascii c,这实际上会引入更多错误字符。您可能需要关闭universal\u新行,并根据需要对脚本进行编码。例如stdout,stderr=p.communicate(scpt.encode('utf-8'))
然后stdout.decode('utf-8'))
。在python 3中,如果脚本包含非ascii字符,则此操作将失败。更好的方法是执行universal\u newlines=False
,然后对脚本进行编码,并根据需要解码stdout
。python 3.6要求将,capture\u output=True
部分从子进程中删除。运行此操作p如果在Popen参数的末尾添加了universal\u newlines=True
,则ython 3.6将正常运行
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')
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)
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())