Set Windows Environment Variable

Duncan Booth duncan.booth at invalid.invalid
Thu Mar 30 12:24:49 EST 2006


Fuzzyman wrote:

> 
> Magnus Lycka wrote:
>> Surely there must be a way to programatically set up the
>> environment variables for not yet started processes? I.e.
>> doing the same as when you manually change things in the
>> control panel. I'm pretty sure many Windows installers do
>> that, and while I suppose this is technically a registry
>> manipulation, I suspect there is a more direct API somewhere.
> 
> I *believe* that ``SetEnvironmentVariable`` exists in the underlying
> windows API, but that it isn't wrapped by the win32api extension.
> 
> I may be wrong.
> 
No, there is a SetEnvironmentVariable call which sets environment variables 
for the current process. From the documentation:

"This function has no effect on the system environment variables or the 
environment variables of other processes."

I don't think it will have much effect on the currently running Python 
process either since the you just access os.environ and that won't see 
changes to the system's idea of the environment.

Magnus:
I took the original question as asking about already running processes. If 
the question was about processes which have not yet been started then the 
following may be of use:

"Calling SetEnvironmentVariable has no effect on the system environment 
variables. The user can add or modify system environment variables using 
the Control Panel. To programmatically add or modify system environment 
variables, add them to the 
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session 
Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE 
message. This allows applications, such as the shell, to pick up your 
updates. Note that environment variables listed in this key are limited to 
1024 characters."

This would change the environment for any processes which respond to the 
WM_SETTINGCHANGE message, and consequently any processes which they start. 
Window's explorer will then update its environment so that future processes 
that it starts will pick up the changes. I think that most other 
applications, including window's CMD.EXE shell won't respond to this 
message so you wouldn't see the changes in future processes they start.

See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/55993 for how 
to do this from Python.



More information about the Python-list mailing list