/recipes/Python/576437_Changing_shortcut_usb_key/recipe-576437.py

https://github.com/ActiveState/code
Python | 71 lines | 38 code | 11 blank | 22 comment | 3 complexity | 54a1ac6cb34ca6037725275da5139fd2 MD5 | raw file
  1. import sys,glob,re
  2. import pythoncom
  3. from win32com.shell import shell
  4. import win32com
  5. import win32com.client
  6. import string
  7. """
  8. By bussiere bussiere @at gmail.com
  9. thanks to :
  10. http://www.blog.pythonlibrary.org/
  11. http://www.blog.pythonlibrary.org/?p=21
  12. and :
  13. http://codesnippets.joyent.com/tag/python
  14. http://codesnippets.joyent.com/tag/python#post529
  15. """
  16. __Author__ ="bussiere"
  17. __Email__ = "bussiere @at gmail.com"
  18. __Titre__ = "Changing shortcut on a usb key v2"
  19. __Description__ = "Changing the drive of a list of shortcut automatically must be placed in the shortcut directory on the usb key"
  20. __Discussion__ = "i've made some shortcut on my usb key for http://www.launchy.net/ launchy and i had always to change them if on one pc the usb drive was i: on an other it was k: it was such a pain each time. Now it change all the shortcut automatically."
  21. __Tags__ ="Usb shortcut windows key raccourcis"
  22. class Win32Shortcut:
  23. def __init__(self, lnkname):
  24. self.shortcut = pythoncom.CoCreateInstance(
  25. shell.CLSID_ShellLink, None,
  26. pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
  27. self.shortcut.QueryInterface(pythoncom.IID_IPersistFile).Load(lnkname)
  28. def __getattr__(self, name):
  29. return getattr(self.shortcut, name)
  30. def main():
  31. shell2 = win32com.client.Dispatch('WScript.Shell')
  32. # here we just get the drive where is the usb key
  33. drive = sys.path[0][0:2]
  34. #here we list all the file on the shortcut directory
  35. files = glob.glob(sys.path[0]+'/*')
  36. # here we take one file path
  37. path = glob.glob(sys.path[0])[0]
  38. #we normalize the path for python
  39. path = string.replace(path,'\\','\\\\')
  40. # we prepare a regexp for finding the shortcuts
  41. p = re.compile('\.lnk')
  42. for file in files :
  43. # we list all the files and find the shortcuts .lnk
  44. if p.search(file) :
  45. # we get the shortcut
  46. s = Win32Shortcut(file)
  47. #we take the target directory of the shortcut
  48. itemPath = s.GetPath(0)[0]
  49. #we normalize the path of the shortcut
  50. file = string.replace(file,'\\','\\\\')
  51. # we overwrite the shortcut (same directory, same name).
  52. shortcut = shell2.CreateShortCut(file)
  53. #we replace the target path (drive = usb drive, path without the drive = itemPath[2:])
  54. shortcut.Targetpath = drive + itemPath[2:]
  55. #we set the directory drive
  56. shortcut.WorkingDirectory = path
  57. #we save the shortcut
  58. shortcut.save()
  59. if __name__ == "__main__":
  60. main()