win_add2path.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 = "%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. usersite = site.USER_SITE.replace(appdata, "%APPDATA%")
  21. userpath = os.path.dirname(usersite)
  22. userscripts = os.path.join(userpath, "Scripts")
  23. else:
  24. userscripts = None
  25. with winreg.CreateKey(HKCU, ENV) as key:
  26. try:
  27. envpath = winreg.QueryValueEx(key, PATH)[0]
  28. except OSError:
  29. envpath = DEFAULT
  30. paths = [envpath]
  31. for path in (pythonpath, scripts, userscripts):
  32. if path and path not in envpath and os.path.isdir(path):
  33. paths.append(path)
  34. envpath = os.pathsep.join(paths)
  35. winreg.SetValueEx(key, PATH, 0, winreg.REG_EXPAND_SZ, envpath)
  36. return paths, envpath
  37. def main():
  38. paths, envpath = modify()
  39. if len(paths) > 1:
  40. print("Path(s) added:")
  41. print('\n'.join(paths[1:]))
  42. else:
  43. print("No path was added")
  44. print("\nPATH is now:\n%s\n" % envpath)
  45. print("Expanded:")
  46. print(winreg.ExpandEnvironmentStrings(envpath))
  47. if __name__ == '__main__':
  48. main()