如何将AppleScript函数中的全局变量用于Python代码 [英] How to use global variables inside of an Applescript function for a Python code

查看:0
本文介绍了如何将AppleScript函数中的全局变量用于Python代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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,您还可以选择py-applescript,即supportedappscript,即not。如果您需要将复杂参数传递给AppleScrip,py-applescript库会自动在常见的AS和Python类型之间进行转换。AppSCRIPT完全避免使用AppleScrip,但这要靠您自己。

这篇关于如何将AppleScript函数中的全局变量用于Python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆