Skip to content

Instantly share code, notes, and snippets.

@apetrone
Last active May 14, 2022 14:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apetrone/5937002 to your computer and use it in GitHub Desktop.
Save apetrone/5937002 to your computer and use it in GitHub Desktop.
Set win32 environment variable on startup via python
# This must be run with Administrator privileges in order to set environment variables
# http://code.activestate.com/recipes/55993/, Wolfgang Strobl
import _winreg
import sys
import traceback
import win32gui
import win32api
# this ensures that changes propagate immediately
def RefreshEnvironment():
""" A method by Geoffrey Faivre-Malloy and Ronny Lipshitz """
# broadcast settings change
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 0x0002
sParam = "Environment"
res1, res2 = win32gui.SendMessageTimeout( HWND_BROADCAST, WM_SETTINGCHANGE, 0, sParam, SMTO_ABORTIFHUNG, 100 )
if not res1:
print( "result: %s, %s, from SendMessageTimeout" % (bool(res1), res2) )
def SetSystemEnvironmentVariable( name, value ):
try:
# connect
reg = _winreg.ConnectRegistry( None, _winreg.HKEY_LOCAL_MACHINE )
env = _winreg.OpenKey( reg, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", 0, _winreg.KEY_ALL_ACCESS )
# set the value
_winreg.SetValueEx( env, name, 0, _winreg.REG_EXPAND_SZ, value )
# cleanup
_winreg.CloseKey( env )
_winreg.CloseKey( reg )
# make sure changes propagate immediately. Without this call,
# changes will appear under the Properties and Environment Variables,
# but new command prompts do not reflect these changes
RefreshEnvironment()
except:
traceback.print_exc( file=sys.stdout )
# this script will update the PATH environment variable to include these paths
paths = []
paths.append( r"c:\python27" )
paths.append( r"c:\python27\scripts" )
paths.append( r"c:\cygwin\bin" )
# compile the new path
current_path = win32api.GetEnvironmentVariable( 'PATH' )
for path in paths:
current_path += ';' + path
# set the path
SetSystemEnvironmentVariable( 'PATH', current_path )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment