You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.6 KiB

  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. 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()