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