问题
I'm quite new to programming, but I've learned some basic Python programming in a university course.
I'm looking for a way to run very simple Python scripts on Mac applications (mainly iTunes), in lieu of AppleScript. I've read up on using AppScript for Python, but it is no longer in development and is broken as of iTunes 10.6.3.
On my Windows computer, I was easily able to script applications with Python using a module called PyWin32. Since switching to a Mac, however, I haven't been able to find a good alternative. Here is an example script that I used on Windows, just to give an idea of the simplicity of the scripts I would like to use:
from win32com.client import Dispatch
iTunes = Dispatch("iTunes.Application")
selected_tracks = iTunes.SelectedTracks
track_count = selected_tracks.Count
for i in range(1, track_count + 1):
selected_tracks.Item(i).TrackNumber = i
selected_tracks.Item(i).TrackCount = track_count
As you can see, my scripting needs are quite basic, and I don't need any of the advanced event-handling features of something like AppScript. I plan on eventually learning AppleScript, but right now I still feel most comfortable with Python. Does anyone have any suggestions?
Thanks a lot!
回答1:
You need to use Scripting Bridge with PyObjC. There's rather a lot to it, but those links will get you started.
回答2:
One possibility is to use osascript through the subprocess module. You can then have a small amount of AppleScript to access, e.g., application properties you need, but keep the logic in Python. Often, you can find online examples of the needed AppleScript reference forms, which avoids a need to dig deeply into AppleScript.
回答3:
For when you start learning AppleScript ;)
tell application "iTunes"
set selected_tracks to selection
set track_count to count of selected_tracks
repeat with i from 1 to track_count
set a_track to item i of selected_tracks
set a_track's track number to i
set a_track's track count to track_count
end repeat
end tell
来源:https://stackoverflow.com/questions/13852864/using-python-with-scriptable-applications-on-a-mac