本文介绍了如何在 Python 脚本中嵌入 AppleScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 Python 脚本中嵌入 AppleScript.我不想将 AppleScript 保存为文件,然后将其加载到我的 Python 脚本中.有没有办法在 Python 中将 AppleScript 作为字符串输入并让 Python 执行 AppleScript?非常感谢.
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()
推荐答案
使用 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)
这篇关于如何在 Python 脚本中嵌入 AppleScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!