Created
May 8, 2009 19:22
-
-
Save erickedji/108952 to your computer and use it in GitHub Desktop.
Script to presistently set environment vars on Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from _winreg import * | |
import os, sys, win32gui, win32con | |
class Penv: | |
def __init__(self): | |
path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' | |
self.reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) | |
self.regKey = OpenKey(self.reg, path, 0, KEY_ALL_ACCESS) | |
def query(self, name): | |
value, type_id = QueryValueEx(self.regKey, name) | |
return value | |
def set(self, name, value): | |
if name.upper() == 'PATH': | |
value = self.query(name) + ';' + value | |
SetValueEx(self.regKey, name, 0, REG_EXPAND_SZ, value) | |
def delete(self, name): | |
DeleteValue(self.regKey, name) | |
def show(self): | |
for i in range(1024): | |
try: | |
n,v,t = EnumValue(self.regKey, i) | |
print '%s=%s' % (n, v) | |
except EnvironmentError: | |
break | |
def __del__(self): | |
win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment') | |
CloseKey(self.regKey) | |
CloseKey(self.reg) | |
def main(): | |
try: | |
e = Penv() | |
if len(sys.argv) == 1: | |
e.show() | |
else: | |
name, value = sys.argv[1].split('=') | |
if value: | |
e.set(name, value) | |
else: | |
e.delete(name) | |
except Exception, ex: | |
print ex | |
if __name__=='__main__': | |
usage = \ | |
""" | |
Usage: | |
Show all environment variables: | |
$ pyhton env.py | |
Add/Modify/Delete environment variable | |
$ python env.py <name>=[value] | |
If <name> is PATH env.py will append the value prefixed with ; | |
If there is no value env.py will delete the <name> environment variable | |
Note that the current command window will not be affected, | |
only new command windows. | |
""" | |
argc = len(sys.argv) | |
if argc > 2 or (argc == 2 and sys.argv[1].find('=') == -1): | |
print usage | |
sys.exit() | |
main() | |
# Using this script taken form the ASPN cookbook really helped me grok somme important questions. | |
# It was a plain procedural script, with the registry tree passed to every fonction. Using a class | |
# allowed me to: | |
# - exploit RAII (Resource acquisition is initialisation ): the connection to the registry is opened | |
# when the objet is instantiated, and destroyed when the instance goes out of scope. | |
# - get rid of somme globals, by making them instance attributes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment