Setting a global environment variable

I’ve been trying to research this but haven’t come to a solid conclusion. How does one set(create) and environment variable using python?

I found the “set” command at first, but then I learned that is only for the current running shell. Then I found the “setx” command, and read that it was released in sp2 of winxp as an extended tool set, so not sure if that works for win7 or if a user would even know how to get it. Then I saw something about PowerShell, but again trying to keep the install as simple as possible for the artists.

The reason I want to know this is, I want to have a dialog box where the user can select a directory to install and have it set the variable behind the scenes so they don’t have to do it.

Thanks in advance

Environment Variables are stored in the registry. So creating one in python will look like this:


import _winreg

key = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
hkey = _winreg.OpenKey(key, 'Environment', 0, _winreg.KEY_SET_VALUE)

_winreg.SetValueEx(hkey, 'NEW_ENV_VARIABLE', 0, _winreg.REG_SZ, r'C:\Temp')

_winreg.CloseKey(key)
_winreg.CloseKey(hkey)

Though for an application install path you may not need an environment variable unless you really want to do it that way. Most apps remember them in a key, for example:

HKEY_LOCAL_MACHINE
SOFTWARE\Autodesk\Maya\2012\Setup\InstallPath
MAYA_INSTAll_LOCATION

Stev

1 Like

x

Just to make sure I understand correctly. Stev, is this the same as if I went to the advanced tab under MyComputer properties and set a new variable there? When I refer to “install” it really meant just copying some folders manually, thats why I need to create a way to setup an easy creation method for env. vars.

On Windows you don’t need to muck about with the registry to change/add/remove environment variables. Import the os module and deal directly with the os.environ dictionary. The keys of that dictionary are the env var names and the values are the env var values. Python on Windows supports os.putenv(), which commits environment variables to the system. os.putenv() will be called automatically any time you modify the os.environ dictionary.

Yes, this is the same as creating a variable in My Computer Properties.

@Jeff
My understanding was that using os doesn’t permanently create or change an environment variable, it’ll only last for the current application session. If there is a way to use os then that’d be much nicer.

after mucking with the registry though, you’ll need to tell windows to refresh the environment. it doesn’t do this automatically.

to do this you need to call:
win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, ‘Environment’, win32con.SMTO_ABORTIFHUNG, 100)

or something similar. if you don’t do this the registry will change, but new processes won’t pick up those environment changes.

Whoa I remember having that problem, I hadn’t put the code into practice yet.

Thanks Zoo!

I had to use ctypes since I can’t use win32com or gui (long story). Thanks again.


from ctypes import *

HWND_BROADCAST = 65535
WM_SETTINGCHANGE = 26
SMTO_ABORTIFHUNG = 2

result = c_long()
user32dll = windll.user32

user32dll.SendMessageTimeoutA(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 'Environment', SMTO_ABORTIFHUNG, 100, byref(result))

Stev

Couple things =)

SET sucks, use SETX (this makes it persist).

Also, if you do not want to depend on win32 (especially if you are doing this from a 64bit environment), use the REG command:


args = ['REG', 'delete', 'HKCU\Environment', '/V', 'key-name-here', '/f']
if subprocess.call(args, shell=1, stdout=subprocess.PIPE)==0:
     """do something magical""""

I also use the subprocess approach with SETX.

I’ll post a dirty hacker file we use to switch environments for certain teams:

http://www.onarom.com/envSetup.py

HTH

If I were you I’d avoid setting sysEnv’s on individual machines and do it at app launch.

Down the road it becomes a pain in the ass.

Remember you can create EnvVars in a shell and launch maya or apps through that. They are not perm and you can change a single distributable batch to everyone at will or have many depending on projects you run.
Its a little cleaner and more reliable not to mention quicker to set up new people.

Thats good to know then. I don’t mind doing that and it makes more sense to not make it permanent anyway. Thanks for the input everyone!

[QUOTE=Jeff Hanna;10483]On Windows you don’t need to muck about with the registry to change/add/remove environment variables. Import the os module and deal directly with the os.environ dictionary. The keys of that dictionary are the env var names and the values are the env var values. Python on Windows supports os.putenv(), which commits environment variables to the system. os.putenv() will be called automatically any time you modify the os.environ dictionary.

http://docs.python.org/library/os.html[/QUOTE]

:nod::nod::nod::nod:

[QUOTE=Ishindenshin;10783]Quote:
Originally Posted by Jeff Hanna
On Windows you don’t need to muck about with the registry to change/add/remove environment variables. Import the os module and deal directly with the os.environ dictionary. The keys of that dictionary are the env var names and the values are the env var values. Python on Windows supports os.putenv(), which commits environment variables to the system. os.putenv() will be called automatically any time you modify the os.environ dictionary.

[/QUOTE]

Just be careful. If you are using a python interpreter from something else like Maya, the environment is gathered and set before Maya python loads.

the OS module can manipulate the environment, but then you are also required to modify the Maya environment (for example) after it starts if you using something like os.

sitecustomize and/or persisting the environment, OR, doing as someone else mentioned and launching python, modify the environment, then launch an app from the python session, are simple entry points so you only have to modify the environment once.

=)

Yes the env can be set using a shell script before maya starts to either temporarily or more persistently set env with setx as someone pointed out. I’m not sure if this the exact technique that will most satisfy the parameters of the situation but I thought it might be an option to consider at least.

Hah, unfortunately on Win7 setx does not work if your %PATH% is longer than 1024 bytes (while by the OS 2048 should be fine). Most of our programmer workstations have a PATH variable longer than 1024 bytes. :slight_smile:

Instead, setx will just say it truncated your path to 1024 bytes. And it wrote it successfully. Gotta love this OS. :slight_smile:

So, I’d recommend to not use setx on a global system-wide scale. It’s borked. :slight_smile:

SamiV.

Have you tried writing a super-simple setx in .NET and seeing if there’s the same truncation?

My understanding is that using the OS will not permanently change the environment variables created or last year alone for the current application session. If there is a way to use the OS, it will be much better.

[QUOTE=Amorano;10488]

http://www.onarom.com/envSetup.py

HTH[/QUOTE]

Link broken?

We startup Maya using a python process and it works great. When calling Maya from the command line you can pass it a script to run at startup time. This freed us from relying on the userSetup.mel file, giving individual users the ability to customize maya further and also allows us to run a factory-installed version of maya by using the normal application shortcut (which is awesome for testing bugs/crashes).