/Tools/scripts/win_add2path.py

http://unladen-swallow.googlecode.com/ · Python · 57 lines · 41 code · 8 blank · 8 comment · 12 complexity · 1f34d808dde6b7def628b9343491ac65 MD5 · raw file

  1. """Add Python to the search path on Windows
  2. This is a simple script to add Python to the Windows search path. It
  3. modifies the current user (HKCU) tree of the registry.
  4. Copyright (c) 2008 by Christian Heimes <christian@cheimes.de>
  5. Licensed to PSF under a Contributor Agreement.
  6. """
  7. import sys
  8. import site
  9. import os
  10. import _winreg
  11. HKCU = _winreg.HKEY_CURRENT_USER
  12. ENV = "Environment"
  13. PATH = "PATH"
  14. DEFAULT = u"%PATH%"
  15. def modify():
  16. pythonpath = os.path.dirname(os.path.normpath(sys.executable))
  17. scripts = os.path.join(pythonpath, "Scripts")
  18. appdata = os.environ["APPDATA"]
  19. if hasattr(site, "USER_SITE"):
  20. userpath = site.USER_SITE.replace(appdata, "%APPDATA%")
  21. userscripts = os.path.join(userpath, "Scripts")
  22. else:
  23. userscripts = None
  24. with _winreg.CreateKey(HKCU, ENV) as key:
  25. try:
  26. envpath = _winreg.QueryValueEx(key, PATH)[0]
  27. except WindowsError:
  28. envpath = DEFAULT
  29. paths = [envpath]
  30. for path in (pythonpath, scripts, userscripts):
  31. if path and path not in envpath and os.path.isdir(path):
  32. paths.append(path)
  33. envpath = os.pathsep.join(paths)
  34. _winreg.SetValueEx(key, PATH, 0, _winreg.REG_EXPAND_SZ, envpath)
  35. return paths, envpath
  36. def main():
  37. paths, envpath = modify()
  38. if len(paths) > 1:
  39. print "Path(s) added:"
  40. print '\n'.join(paths[1:])
  41. else:
  42. print "No path was added"
  43. print "\nPATH is now:\n%s\n" % envpath
  44. print "Expanded:"
  45. print _winreg.ExpandEnvironmentStrings(envpath)
  46. if __name__ == '__main__':
  47. main()