如何从 Python 中的 AppleScript 获取 return 值?

How to get return value from AppleScript in Python?

我需要获取 Python 中 window 的大小并将其分配给变量。我正在尝试这样做:

windowSize = '''
    tell application "System Events" to tell application process "%(app)s"
    get size of window 1
    end tell
    ''' % {'app': app} // app = "Terminal


(wSize, error) = Popen(['osascript', '/Setup.scpt'], stdout=PIPE).communicate()
print("Window size is: " + wSize)

我只收到这个错误:TypeError: can only concatenate str (not "bytes") to str

我是 Python 的新手,所以我希望你能帮助我

您需要将您的 AppleScript(即 windowSize)作为输入传递给 Popen.communicate():

示例:

from subprocess import Popen, PIPE

app = "Terminal"

windowSize = '''
    tell application "%(app)s"
      get size of window 1
    end tell
  ''' % {'app': app}

proc = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
wSize, error = proc.communicate(windowSize)
print("Window size is: " + wSize)

备注:

  • 在您的 windowSize AppleScript 中,不必 tell application "System Events" to tell ... - 您可以 tell application "%(app)s" 代替。但是,假设在“系统偏好设置”中启用了辅助设备访问,您的 AppleScript 仍然有效。

  • 这会将类似以下内容记录到控制台:

    Window size is: 487, 338

    您可能需要考虑在 print 语句中使用 str.replace() 将逗号 (,) 替换为 x。例如,将上面要点中的 print 语句更改为:

    print("Window size is: " + wSize.replace(",", " x"))
    

    将改为打印如下内容:

    Window size is: 487 x 338

  • 如果您想用一行(类似于您的 OP)替换上面要点中以 procwSize) 开头的两行代码,然后替换他们改为:

    (wSize, error) = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True).communicate(windowSize)
    
  • 要获得 windows widthheight 作为两个单独的变量,您随后可以使用str.split() 方法拆分 wSize 变量(使用字符串 ", " 作为分隔符)。例如:

    # ...
    wWidth = wSize.split(", ")[0]
    wHeight = wSize.split(", ")[1]
    
    print("Window width is: " + wWidth)
    print("Window height is: " + wHeight)