首页 > 解决方案 > 如何从 Python 中的 AppleScript 获取返回值?

问题描述

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

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 完全陌生,所以我希望你能帮助我

标签: pythonapplescriptappkit

解决方案


您需要将 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)

备注

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

  • 这将在控制台中记录如下内容:

    Window size is: 487, 338

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

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

    将打印这样的东西:

    Window size is: 487 x 338

  • 如果您想用一行(类似于您的 OP)替换上面 gist 中以procand开头的两行代码,wSize然后将它们替换为以下内容:

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

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

推荐阅读