我试图让我的程序自动关联某些要由它打开的文件扩展名,但我不确定如何在 MacOSX 中做到这一点。我不是在问如何在 GUI 中将程序与文件扩展名相关联,我希望能够将它编程到我的程序中。
4 回答
要向应用程序注册新的文件扩展名,请使用以下默认命令。
将 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
在此处查找 CFBundleDocumentTypes Info.plist 键的描述:
-K
如果您右键单击您的 .app 文件并选择“显示包内容”,将有一个名为 的文件夹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 文档”)。
此外,您可以在此处查看其他值的含义以及是否需要更改它们。那里还列出了其他值,如果需要,您可以添加它们。
这涉及通过 py2app 捆绑您的应用程序,将某些密钥添加到您的 Info.plist 文件并在您的应用程序中安装事件处理程序。