Search code examples
pythonapplescriptappkit

How to get return value from AppleScript in Python?


I need to get size of the window in Python and assign it to the variable. I'm trying with this:

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)

I get this error only: TypeError: can only concatenate str (not "bytes") to str

I'm completely new to Python so I hope you can help me with it


Solution

  • You'll need to pass your AppleScript (i.e. windowSize) as input to Popen.communicate():

    Example:

    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)
    

    Notes:

    • In your windowSize AppleScript it shouldn't be necessary to tell application "System Events" to tell ... - you can just tell application "%(app)s" instead. However, you're AppleScript still works assuming Access for assistive devices is enabled in System Preferences.

    • This will log something like the following to the console:

      Window size is: 487, 338

      You may want to consider utilizing str.replace() in your print statement to replace the comma (,) with an x. For instance, changing print statement in the gist above to this:

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

      will print something like this instead:

      Window size is: 487 x 338

    • If you wanted to replace the two lines of code in the gist above which begin with proc and wSize) with one line (similar to your OP) then replace them with the following instead:

      (wSize, error) = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True).communicate(windowSize)
      
    • To get the windows width and height as two separate variables you could subsequently utilize the str.split() method to split the wSize variable (using the string ", " as the delimiter). For instance:

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