shortcut.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """Creation of Windows shortcuts.
  4. Requires win32all.
  5. """
  6. from win32com.shell import shell
  7. import pythoncom
  8. import os
  9. def open(filename):
  10. """Open an existing shortcut for reading.
  11. @return: The shortcut object
  12. @rtype: Shortcut
  13. """
  14. sc=Shortcut()
  15. sc.load(filename)
  16. return sc
  17. class Shortcut:
  18. """A shortcut on Win32.
  19. >>> sc=Shortcut(path, arguments, description, workingdir, iconpath, iconidx)
  20. @param path: Location of the target
  21. @param arguments: If path points to an executable, optional arguments to
  22. pass
  23. @param description: Human-readable description of target
  24. @param workingdir: Directory from which target is launched
  25. @param iconpath: Filename that contains an icon for the shortcut
  26. @param iconidx: If iconpath is set, optional index of the icon desired
  27. """
  28. def __init__(self,
  29. path=None,
  30. arguments=None,
  31. description=None,
  32. workingdir=None,
  33. iconpath=None,
  34. iconidx=0):
  35. self._base = pythoncom.CoCreateInstance(
  36. shell.CLSID_ShellLink, None,
  37. pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink
  38. )
  39. data = map(None,
  40. ['"%s"' % os.path.abspath(path), arguments, description,
  41. os.path.abspath(workingdir), os.path.abspath(iconpath)],
  42. ("SetPath", "SetArguments", "SetDescription",
  43. "SetWorkingDirectory") )
  44. for value, function in data:
  45. if value and function:
  46. # call function on each non-null value
  47. getattr(self, function)(value)
  48. if iconpath:
  49. self.SetIconLocation(iconpath, iconidx)
  50. def load( self, filename ):
  51. """Read a shortcut file from disk."""
  52. self._base.QueryInterface(pythoncom.IID_IPersistFile).Load(filename)
  53. def save( self, filename ):
  54. """Write the shortcut to disk.
  55. The file should be named something.lnk.
  56. """
  57. self._base.QueryInterface(pythoncom.IID_IPersistFile).Save(filename, 0)
  58. def __getattr__( self, name ):
  59. if name != "_base":
  60. return getattr(self._base, name)
  61. raise AttributeError("%s instance has no attribute %s" % (
  62. self.__class__.__name__, name))