由网友(冷暖自知)分享简介:如何在Tell应用程序内从我的Python脚本调用全局变量?这里是一个例子,说明了这一点可能会发生什么。假设我想从AppleScrip外部从一个全局python变量更改所有的";前窗口&。这怎么可能发生?import subprocessdef get_window_title():cmd = """tell...![Python函数基础](https://p.xsw88.cn/allimgs/daicuo/20230903/2626.png)
如何在Tell应用程序内从我的Python脚本调用全局变量?这里是一个例子,说明了这一点可能会发生什么。假设我想从AppleScrip外部从一个全局python变量更改所有的";前窗口&。这怎么可能发生?
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())
推荐答案
如果您想要将参数传递到AppleScrip中,下面是正确的方法:
#!/usr/bin/env python3
import subprocess
scpt = """
on run {arg1, arg2}
return arg1 + arg2
end run
"""
arg1 = 37
arg2 = 5
proc = subprocess.Popen(['osascript', '-', str(arg1), str(arg2)],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding='utf8')
out, err = proc.communicate(scpt)
print(out) # 42
![Python函数基础](https://p.xsw88.cn/allimgs/daicuo/20230903/2626.png)
由于您使用的是Python,您还可以选择py-applescript,即supported或appscript,即not。如果您需要将复杂参数传递给AppleScrip,py-applescript
库会自动在常见的AS和Python类型之间进行转换。AppSCRIPT完全避免使用AppleScrip,但这要靠您自己。
相关推荐
最新文章