Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanently altering a user's %PATH% environment variable via batch or Python

I've been having difficulty with getting my users to set the PATH environment variable manually, I'm looking for a way to do this automatically. A batch file would be preferable, since that would require them to run it themselves (with a warning as to what they're doing), but an addition to the setup.py is acceptable as well.

Other information: SET only affects the current and derivative shells; the permanent values seem to be stored in the Registry somewhere (a place where I dare not tread).

like image 801
Xiong Chiamiov Avatar asked Jul 21 '09 00:07

Xiong Chiamiov


People also ask

How do you set a permanent environment variable in Python?

To set and get environment variables in Python you can just use the os module: import os # Set environment variables os. environ['API_USER'] = 'username' os. environ['API_PASSWORD'] = 'secret' # Get environment variables USER = os.

How do I change an environment variable in Python?

To permanently modify the default environment variables, click Start and search for 'edit environment variables', or open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you can add or modify User and System variables.

How do I set an environment variable in a batch file?

When creating batch files, you can use set to create variables, and then use them in the same way that you would use the numbered variables %0 through %9. You can also use the variables %0 through %9 as input for set. If you call a variable value from a batch file, enclose the value with percent signs (%).


2 Answers

I just ran across this question and didn't like any of the available options so I decided to write my own solution.

(SetEnv would've been good, but I didn't like the non-libre license and I always prefer not having to call a subprocess... I wouldn't mind calling SetEnv as a subprocess but, according to Wikipedia, the license it uses is non-libre because it has some kind of "do no evil" clause and that kind of legally-ambiguous restriction is always a ticking time-bomb in my opinion.)

Here's a little MIT-licensed Python class to hide away the work of modifying the registry directly and sending the WM_SETTINGCHANGE. (Good for use in setup.py)

like image 176
ssokolow Avatar answered Nov 15 '22 16:11

ssokolow


So, since I've been having difficulty with getting my users to set the PATH manually, I'm looking for a way to do this automatically.

The HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths (as well as HKEY_CURRENT_USER\...) registry key allows you to attach an application specific path to your executable name.

Whenever an executable of the given name is started, the application specific path is added to that executable's PATH environment variable.

like image 26
mrsheen Avatar answered Nov 15 '22 16:11

mrsheen