【问题标题】:How to get return value from AppleScript in Python?如何从 Python 中的 AppleScript 获取返回值?
【发布时间】:2018-08-09 20:16:04
【问题描述】:

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

【问题讨论】:

    标签: python applescript appkit


    【解决方案1】:

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

    • 如果您想将上述要点中以 procwSize 开头的两行代码替换为一行(类似于您的 OP),则将它们替换为以下代码:

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

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

    【讨论】:

      猜你喜欢
      • 2015-05-11
      • 1970-01-01
      • 2011-10-17
      • 2018-04-15
      • 2013-09-07
      • 1970-01-01
      相关资源
      最近更新 更多