Thu 25 Feb 2010
Back when I first wrote about creating shortcuts with Python last month, I kept thinking to myself that I had a 3rd way of doing it. Today, I had to maintain some of my shortcut code and I stumbled upon it once more. I also noticed that my post had received a comment from Tim Golden on yet another way to create shortcuts, so I’ll include that in this post as well.
Oddly enough, my other method happened to use something of Tim Golden’s; namely, his winshell module. Check it out below:
import os import winshell program_files = winshell.programs() winshell.CreateShortcut ( Path=os.path.join (program_files, 'My Shortcut.lnk'), Target=r'C:\Program Files\SomeCoolProgram\prog.exe')
Let’s unpack this so you know what’s going on. First, we use winshell to find the user’s “Programs” folder, which is a sub-folder of the user’s “Startup” folder. Then we use winshell’s CreateShortcut method to actually create the shortcut. If you look at the CreateShortcut’s docstring, you’ll discover that it can also accept the following keyword arguments: Arguments, StartIn, Icon, and Description.
Oddly enough, this wasn’t the method that Golden was suggesting in his comment. He had another idea that is quite a bit more complicated. Let’s take a quick look:
import os, sys import pythoncom from win32com.shell import shell, shellcon shortcut = pythoncom.CoCreateInstance ( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink ) program_location = r'C:\Program Files\SomeCoolProgram\prog.exe' shortcut.SetPath (program_location) shortcut.SetDescription ("My Program Does Something Really Cool!") shortcut.SetIconLocation (program_location, 0) desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0) persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile) persist_file.Save (os.path.join (desktop_path, "My Shortcut.lnk"), 0)
In my opinion, this is getting a little too low-level for my taste. However, it is also really cool that you can do it this way. If you look at Tim Golden’s linked page, you’ll see that this example is practically just a copy and paste job. I think winshell’s desktop method does the same thing as “shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)” and it’s easier to read. Anyway, the code above does the same thing that the previous code does, only it puts the shortcut on the user’s desktop. I don’t really understand what Golden is doing in the “pythoncom.CoCreateInstance” part other than creating an object that we can use to create our shortcut.
Also note that Tim Golden talks about creating a URL shortcut using a method that is quite similar to the one detailed above. You can go to his website and learn all the juicy details.
Anyway, I felt that to be complete, I’d better write up these other two methods of creating shortcuts in Windows. Hopefully you found this interesting and maybe even educational.