faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

22 of 40 people (55%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Creating Windows shortcuts (.lnk)

Aug 9th, 2008 02:17
Sek Tea, Nathan Wallace, Hans Nowak, Snippet 286, Mike Fletcher


"""
Packages: operating_systems.windows
"""
"""
I'm just trying to find an easy to create shortcuts on Windows platforms
through Python... it doesn't seem to be a simple matter though.  I've gone
through all the Win32 docs, and found nothing, and have started writing
(with limited success) a C function to do it.
Is there an easy way?  q:]
Here's a quicky demo of both creating and reading a lnk file on windows.
There's no real reason for the wrapper class other than that I'm a
raving lunatic and it's 3am :) ...
"""
# link.py
# From a demo by Mark Hammond, corrupted by Mike Fletcher
from win32com.shell import shell
import pythoncom, os
class PyShortcut:
	def __init__( self ):
		self._base = pythoncom.CoCreateInstance(
			shell.CLSID_ShellLink, None,
			pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink
		)
	def load( self, filename ):
		# Get an IPersist interface
		# which allows save/restore of object to/from files
		self._base.QueryInterface( pythoncom.IID_IPersistFile ).Load(filename)
	def save( self, filename ):
		self._base.QueryInterface( pythoncom.IID_IPersistFile ).Save(
          filename, 0)
	def __getattr__( self, name ):
		if name != "_base":
			return getattr( self._base, name )
if __name__=='__main__':
	import sys
	file = sys.argv[1]
	shortcut = PyShortcut()
	if os.path.exists( file ):
		# load and dump info from file...
		shortcut.load( file )
		# now print data...
		print 'Shortcut in file %s to ' \
        +'file:\n\t%s\nArguments:\n\t%s\nDescription:\n\t%s\nWorking '\
        +'Directory:\n\t%s'%(
			file,
			shortcut.GetPath(shell.SLGP_SHORTPATH)[0],
			shortcut.GetArguments(),
			shortcut.GetDescription(),
			shortcut.GetWorkingDirectory()
		)
	else:
		# create the shortcut using rest of args...
		data = map( None, sys.argv[2:], ("SetPath", "SetArguments",
          "SetDescription", "SetWorkingDirectory") )
		for value, function in data:
			if value and function:
				# call function on each non-null value
				getattr( shortcut, function)( value )
		shortcut.save( file )
http://regalos-de-navidad.blogspot.com/
http://regalosdesanvalentin.blogspot.com/
http://ideas-para-regalar.blogspot.com/