Tuesday 30 September 2014

Create Shortcuts using python for windows

I’ve been tasked with creating shortcuts to new applications that need to be placed on the user’s desktop or in their Start Menu or both. In this article, I will show you how to accomplish this task.
I also recommend Tim Golden’s winshell module for creating desktop icon, download winshell for windows from here winshell.

Run below script, it will create desktop shortcut icon.

 import os, winshell
 
desktop = winshell.desktop()
path = os.path.join(desktop, "myNeatWebsite.url")
target = "http://www.google.com/"
 
shortcut = file(path, 'w')
shortcut.write('[InternetShortcut]\n')
shortcut.write('URL=%s' % target)
shortcut.close()

Now check on desktop and click on desktop shortcut icon for executing.

Or you can create shortcut icon by Pythoncom module

  import os, sys
 import pythoncom
 win32com.shell import from 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)

The next example, we will use the win32com module from the PyWin32 package to create a shortcut to Media Player Classic, which is a nice open-source media player.

 import os, winshell
from win32com.client import Dispatch

desktop = winshell.desktop()
path = os.path.join(desktop, "Media Player Classic.lnk")
target = r"P:\Media\Media Player Classic\mplayerc.exe"
wDir = r"P:\Media\Media Player Classic"
icon = r"P:\Media\Media Player Classic\mplayerc.exe"

shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()


 Thanks guys for your support.

2 comments:

  1. For second script, there is a mistake at
    win32com.shell import from shell, shellcon
    It should be
    win32com.shell import shell, shellcon

    It's a small mistake, but i commented to facilitate the newbies.....

    ReplyDelete
  2. For second script, there is a mistake at
    win32com.shell import from shell, shellcon
    It should be
    from win32com.shell import shell, shellcon

    It's a small mistake, but i commented to facilitate the newbies.....

    ReplyDelete