PyObjC AppleScriptKit
This library provides Python wrappers for the AppleScriptKit framework on macOS, allowing Python applications to embed, compile, and execute AppleScript code. It's part of the larger PyObjC project, which maintains a fairly active release cadence, typically releasing minor updates monthly/bi-monthly and major versions annually following macOS SDK updates. The current version is 12.1.
Warnings
- breaking Python 3.9 and earlier are no longer supported by recent PyObjC versions. PyObjC 12.0 dropped support for Python 3.9, and PyObjC 11.0 dropped support for Python 3.8. Ensure your environment meets the `requires_python` spec (currently `>=3.10`).
- breaking PyObjC 11.1 aligned its behavior for initializer methods (e.g., `init` family methods) with `clang`'s Automatic Reference Counting (ARC) documentation. This change affects how references to `self` are handled and returned, potentially altering memory management in custom Objective-C classes implemented in Python.
- gotcha PyObjC (and therefore `pyobjc-framework-applescriptkit`) is exclusively for macOS. It relies heavily on macOS-specific Objective-C frameworks and the Cocoa bridge.
- gotcha PyObjC 11 introduced *experimental* support for free-threading (PEP 703) in Python 3.13. While progress has been made, users attempting to leverage free-threading might still encounter stability issues or unexpected behavior due to the complexity of the Objective-C runtime interacting with Python's new threading model.
- breaking Older frameworks or bindings may be removed in major releases. For example, PyObjC 10.0 removed the `IMServicePlugIn` bindings as the framework was deprecated in macOS 10.13 and removed in macOS 14. Always check release notes for framework removals when upgrading major versions.
Install
-
pip install pyobjc-framework-applescriptkit
Imports
- AppleScriptKit
import AppleScriptKit
- ASAppleScript
from AppleScriptKit import ASAppleScript
Quickstart
import AppleScriptKit
import Foundation # For common Objective-C types like NSError
# Define a simple AppleScript
script_source = '''
display dialog "Hello from PyObjC AppleScriptKit!"
return "Script executed successfully."
'''
# Create an ASAppleScript instance
# Note: In PyObjC, None is used for 'nil' or 'NULL' in Objective-C
error_ptr = None # We'll pass None and check the returned tuple for errors
script = AppleScriptKit.ASAppleScript.alloc().initWithSource_error_(script_source, error_ptr)
if script:
# Execute the script
result, error = script.executeAndReturnError_(error_ptr)
if error:
print(f"Error executing script: {error.localizedDescription()}")
elif result:
print(f"Script result: {result.stringValue()}")
else:
print("Script executed, no result or error reported.")
else:
print("Failed to initialize ASAppleScript object.")