Skip to content

Instantly share code, notes, and snippets.

@jlehikoinen
Last active June 30, 2017 03:56
Show Gist options
  • Save jlehikoinen/842df05ba927deb61117d53156679176 to your computer and use it in GitHub Desktop.
Save jlehikoinen/842df05ba927deb61117d53156679176 to your computer and use it in GitHub Desktop.
Set default application for a file type in macOS
#!/usr/bin/python
"""
set_default_application_for_filetype.py
Description:
Set default application for a file type in macOS
"""
import sys
from LaunchServices import LSCopyDefaultRoleHandlerForContentType
from LaunchServices import LSSetDefaultRoleHandlerForContentType
##### EDIT THIS DICTIONARY ===>
UTI_HANDLER_DICT = {
'org.openxmlformats.spreadsheetml.sheet': 'com.microsoft.Excel',
'com.microsoft.excel.xls': 'com.microsoft.Excel'
}
#####
# Obj-C LSRolesMask constant kLSRolesAll hexadecimal representation is 0xFFFFFFFF
LS_ROLES_MASK = 0xFFFFFFFF
#####
def set_handler():
# Iterate dictionary (key: UTI / content type, value: handler / application)
for content_type, ls_handler in UTI_HANDLER_DICT.iteritems():
# Current
try:
current_handler = LSCopyDefaultRoleHandlerForContentType(content_type, LS_ROLES_MASK)
print "Current handler: %s for content type: %s" % (current_handler, content_type)
except Exception, e:
print e
sys.exit('Could not get current content type handler. Exiting.')
# Change
print 'Changing default handler: %s for content type: %s' % (ls_handler, content_type)
try:
LSSetDefaultRoleHandlerForContentType(content_type, LS_ROLES_MASK, ls_handler)
except Exception, e:
print e
sys.exit('Could not change content type handler. Exiting.')
# New values
try:
new_handler = LSCopyDefaultRoleHandlerForContentType(content_type, LS_ROLES_MASK)
print "New handler: %s for content type: %s" % (new_handler, content_type)
except Exception, e:
print e
sys.exit('Could not get current content type handler. Exiting.')
#####
def main():
set_handler()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment