Search code examples
pythonpython-3.xmacosshortcutshortcut-file

How to use python to create url shortcut on mac?


There are answers to the window version. but not mac.

I have searched google but no appropriate result

let say I want to create a shortcut to google.com on desktop, then we could run the python function

createShortcut("www.google.com","~/Desktop")

what could be the function body?


Solution

  • You can create a macos .url file inside the function. It is formatted as follows:

    [InternetShortcut]
    URL=http://www.yourweb.com/
    IconIndex=0
    

    Here is a sample implementation:

    import os
    
    def createShortcut(url, destination):
        # get home directory if ~ in destination
        if '~' in destination:
            destination = destination.replace('~', os.path.expanduser("~"))
        # macos .url file format
        text = '[InternetShortcut]\nURL=https://{}\nIconIndex=0'.format(url)
        # write .url file to destination
        with open(destination + 'my_shortcut.url', 'w') as fw:
            fw.write(text)
        return
    
    createShortcut("www.google.com", '~/Desktop/')