Search code examples
swiftpython-3.xapplescripttranslatebridge

Is there a Swift bridge for Python?


I developed a script to set attributes for my iTunes music library on my Mac using an Apple Script bridge called AppScript. AppScript Allowed me to write my code in native Python without having to learn Apple Script. AppSript would translate my native Python to Apple Script. Since Apple Script has been replaced with Swift I am wondering if there is a similar bridge for Swift. I have done my research, but no luck. Additionally if there is, can you provide an example of how to control iTunes(now Music) with said library? Thanks in advance


Solution

  • Swift is designed to use MacOS's programming APIs: AppKit, Quartz, CoreFoundation, NSObject, etc, rather than the higher level OSAX event-driven elements (open, print, close, document, window, etc) used in AppleScript.

    The system-bundled python (2.7) comes with pyObjC, which allows python to use the same programming APIs that Swift does, e.g. "writing apps". PyObjC also contains a Scripting Bridge to the AppleScript events and objects. The canonical example code does use iTunes:

    from Foundation import *
    from ScriptingBridge import *
    iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
    print iTunes.currentTrack().name()
    

    (Obvs, this is python2 and you need to put brackets round the print command. Also, personally, I wouldn't import * everything, as it's very slow.)

    Here are some other methods/attributes based on the Script Dictionary:

    iTunes.nextTrack()
    iTunes.previousTrack()
    iTunes.playpause()
    iTunes.fastForward()
    iTunes.setShuffleEnabled_(False)
    iTunes.currentPlaylist().playOnce_(False)
    

    The system-bundled version of pyObjC is very old, but the library itself is still being developed. If you're using python3, then you should install the latest version of pyObjC.

    FWIW, you can actually run uncompiled Swift as a 'script' in the shell.