简体   繁体   English

在可编写脚本的应用程序中使用Python(在Mac上)

[英]Using Python with Scriptable Applications (on a Mac)

I'm quite new to programming, but I've learned some basic Python programming in a university course. 我对编程很陌生,但是我在大学课程中学习了一些基本的Python编程。

I'm looking for a way to run very simple Python scripts on Mac applications (mainly iTunes), in lieu of AppleScript. 我正在寻找一种在Mac应用程序(主要是iTunes)上代替AppleScript来运行非常简单的Python脚本的方法。 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. 我已经阅读了将AppScript用于Python的知识,但是该软件已不再开发,并且从iTunes 10.6.3起已失效。

On my Windows computer, I was easily able to script applications with Python using a module called PyWin32. 在Windows计算机上,我可以使用名为PyWin32的模块轻松地使用Python编写应用程序脚本。 Since switching to a Mac, however, I haven't been able to find a good alternative. 但是,自从改用Mac之后,我一直找不到一个好的选择。 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: 这是我在Windows上使用的示例脚本,目的只是为了让我了解要使用的脚本的简单性:

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. 如您所见,我的脚本需求是非常基本的,并且不需要AppScript之类的任何高级事件处理功能。 I plan on eventually learning AppleScript, but right now I still feel most comfortable with Python. 我打算最终学习AppleScript,但是现在我仍然对Python感到最舒服。 Does anyone have any suggestions? 有没有人有什么建议?

Thanks a lot! 非常感谢!

You need to use Scripting Bridge with PyObjC . 您需要将Scripting BridgePyObjC一起使用。 There's rather a lot to it, but those links will get you started. 有很多事情要做,但是这些链接可以帮助您入门。

One possibility is to use osascript through the subprocess module. 一种可能性是通过子过程模块使用osascript You can then have a small amount of AppleScript to access, eg, application properties you need, but keep the logic in Python. 然后,您可以使用少量的AppleScript进行访问,例如所需的应用程序属性,但是将逻辑保留在Python中。 Often, you can find online examples of the needed AppleScript reference forms, which avoids a need to dig deeply into AppleScript. 通常,您可以在网上找到所需的AppleScript参考表格的示例,从而避免了对AppleScript的深入研究。

For when you start learning AppleScript ;) 当您开始学习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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM