我正在尝试让我的程序自动将某些文件扩展名与它关联,但是我不确定如何在MacOSX中实现。我不是要问如何在GUI中将程序与文件扩展名相关联,而是想将其编程到我的程序中。
我正在尝试让我的程序自动将某些文件扩展名与它关联,但是我不确定如何在MacOSX中实现。我不是要问如何在GUI中将程序与文件扩展名相关联,而是想将其编程到我的程序中。
要将新的文件扩展名与应用程序注册,请使用以下默认命令。
将PUT_FILE_EXTENSION_HERE_WITHOUT_PERIOD替换为文件扩展名,例如txt。
将org.category.program替换为您的程序的com/org名称,例如com.apple.itunes。
$ defaults write com.apple.LaunchServices LSHandlers -array-add \
"<dict><key>LSHandlerContentTag</key>
<string>PUT_FILE_EXTENSION_HERE_WITHOUT_PERIOD</string><key>LSHandlerContentTagClass</key>
<string>public.filename-extension</string><key>LSHandlerRoleAll</key>
<string>org.category.program</string></dict>"
一旦您已将文件扩展名添加到启动服务中,必须重新启动启动服务守护程序,以便它会重新读取配置文件。
您可以运行下面的命令来重新启动启动服务,或者只需重新启动计算机。登录/注销也可能有效,但我没有尝试过。
$ /System/Library/Frameworks/CoreServices.framework/Versions/A/Framework/LaunchServices.framework/Versions/A/Support/lsregister -kill -domain local -domain system -domain user
Contents
的文件夹,在该文件夹中,将会有一个名为 info.plist
的文件和一个名为 Resources
的文件夹(如果其中任何一个不存在,请创建它们)。如果您想要将文件扩展名 .myfileextension
与您的程序关联,并且您希望具有该扩展名的文件拥有包含在名为 icon.icns
的文件中的图标,则将文件 icon.icns
复制到 Resources
文件夹中,并在 info.plist
文件中在 </dict>
标签之前添加以下代码:<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleTypeIconFile</key>
<string>icon.icns</string> <!-- change this -->
<key>CFBundleTypeExtensions</key>
<array>
<string>myfileextension</string> <!-- change this -->
</array>
<key>CFBundleTypeName</key>
<string>File extension description</string> <!-- change this -->
<key>LSHandlerRank</key>
<string>Owner</string>
</dict>
</array>
<!-- change this -->
的行应根据您希望扩展具有的属性进行更改。将 icon.icns
更改为您放置在 Resources
文件夹中并且您希望文件扩展名拥有的图标名称,将 myfileextension
更改为您想要与程序关联的文件扩展名(不含点),将 File extension description
更改为您想要文件扩展名具有的描述(例如对于 .doc 文件,它将是“Microsoft Word 文档”)。我在https://moosystems.com/articles/8-double-click-on-files-in-finder-to-open-them-in-your-python-and-tk-application.html中详细描述了整个过程。
这涉及通过py2app打包您的应用程序,向Info.plist文件添加某些关键内容并在您的应用程序中安装事件处理程序。