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