Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 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 |
Georg Brandl | 38feaf0 | 2008-05-25 07:45:51 +0000 | [diff] [blame] | 13 | import winreg |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 14 | |
Georg Brandl | 38feaf0 | 2008-05-25 07:45:51 +0000 | [diff] [blame] | 15 | HKCU = winreg.HKEY_CURRENT_USER |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 16 | ENV = "Environment" |
| 17 | PATH = "PATH" |
| 18 | DEFAULT = u"%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 | userpath = site.USER_SITE.replace(appdata, "%APPDATA%") |
| 26 | userscripts = os.path.join(userpath, "Scripts") |
| 27 | else: |
| 28 | userscripts = None |
| 29 | |
Georg Brandl | 38feaf0 | 2008-05-25 07:45:51 +0000 | [diff] [blame] | 30 | with winreg.CreateKey(HKCU, ENV) as key: |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 31 | try: |
Georg Brandl | 38feaf0 | 2008-05-25 07:45:51 +0000 | [diff] [blame] | 32 | envpath = winreg.QueryValueEx(key, PATH)[0] |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 33 | except WindowsError: |
| 34 | envpath = DEFAULT |
| 35 | |
| 36 | paths = [envpath] |
| 37 | for path in (pythonpath, scripts, userscripts): |
| 38 | if path and path not in envpath and os.path.isdir(path): |
| 39 | paths.append(path) |
| 40 | |
| 41 | envpath = os.pathsep.join(paths) |
Georg Brandl | 38feaf0 | 2008-05-25 07:45:51 +0000 | [diff] [blame] | 42 | winreg.SetValueEx(key, PATH, 0, winreg.REG_EXPAND_SZ, envpath) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 43 | return paths, envpath |
| 44 | |
| 45 | def main(): |
| 46 | paths, envpath = modify() |
| 47 | if len(paths) > 1: |
| 48 | print "Path(s) added:" |
| 49 | print '\n'.join(paths[1:]) |
| 50 | else: |
| 51 | print "No path was added" |
| 52 | print "\nPATH is now:\n%s\n" % envpath |
| 53 | print "Expanded:" |
Georg Brandl | 38feaf0 | 2008-05-25 07:45:51 +0000 | [diff] [blame] | 54 | print winreg.ExpandEnvironmentStrings(envpath) |
Christian Heimes | 04c420f | 2008-01-18 18:40:46 +0000 | [diff] [blame] | 55 | |
| 56 | if __name__ == '__main__': |
| 57 | main() |