blob: 1c9aedc5ed8dcaeebb88fd895f95c6058bd7f51f [file] [log] [blame]
Christian Heimes04c420f2008-01-18 18:40:46 +00001"""Add Python to the search path on Windows
2
3This is a simple script to add Python to the Windows search path. It
4modifies the current user (HKCU) tree of the registry.
5
6Copyright (c) 2008 by Christian Heimes <christian@cheimes.de>
7Licensed to PSF under a Contributor Agreement.
8"""
9
10import sys
11import site
12import os
Georg Brandl38feaf02008-05-25 07:45:51 +000013import winreg
Christian Heimes04c420f2008-01-18 18:40:46 +000014
Georg Brandl38feaf02008-05-25 07:45:51 +000015HKCU = winreg.HKEY_CURRENT_USER
Christian Heimes04c420f2008-01-18 18:40:46 +000016ENV = "Environment"
17PATH = "PATH"
Georg Brandl64465552010-08-02 22:59:44 +000018DEFAULT = "%PATH%"
Christian Heimes04c420f2008-01-18 18:40:46 +000019
20def 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"):
Steve Dower17be5142015-02-14 09:50:59 -080025 usersite = site.USER_SITE.replace(appdata, "%APPDATA%")
26 userpath = os.path.dirname(usersite)
Christian Heimes04c420f2008-01-18 18:40:46 +000027 userscripts = os.path.join(userpath, "Scripts")
28 else:
29 userscripts = None
30
Georg Brandl38feaf02008-05-25 07:45:51 +000031 with winreg.CreateKey(HKCU, ENV) as key:
Christian Heimes04c420f2008-01-18 18:40:46 +000032 try:
Georg Brandl38feaf02008-05-25 07:45:51 +000033 envpath = winreg.QueryValueEx(key, PATH)[0]
Andrew Svetlov2606a6f2012-12-19 14:33:35 +020034 except OSError:
Christian Heimes04c420f2008-01-18 18:40:46 +000035 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)
Georg Brandl38feaf02008-05-25 07:45:51 +000043 winreg.SetValueEx(key, PATH, 0, winreg.REG_EXPAND_SZ, envpath)
Christian Heimes04c420f2008-01-18 18:40:46 +000044 return paths, envpath
45
46def main():
47 paths, envpath = modify()
48 if len(paths) > 1:
Benjamin Peterson9b86cbc2009-11-09 00:49:19 +000049 print("Path(s) added:")
50 print('\n'.join(paths[1:]))
Christian Heimes04c420f2008-01-18 18:40:46 +000051 else:
Benjamin Peterson9b86cbc2009-11-09 00:49:19 +000052 print("No path was added")
53 print("\nPATH is now:\n%s\n" % envpath)
54 print("Expanded:")
55 print(winreg.ExpandEnvironmentStrings(envpath))
Christian Heimes04c420f2008-01-18 18:40:46 +000056
57if __name__ == '__main__':
58 main()