Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a python script persistently change a Windows environment variable? (elegantly)

Following on from my previous question, is it possible to make a Python script which persistently changes a Windows environment variable?

Changes to os.environ do not persist once the python interpreter terminates. If I were scripting this on UNIX, I might do something like:

set foo=`myscript.py`

But alas, cmd.exe does not have anything that works like sh's back-tick behavior. I have seen a very long-winded solution... it 'aint pretty so surely we can improve on this:

for /f "tokens=1* delims=" %%a in ('python  ..\myscript.py') do set path=%path%;%%a

Surely the minds at Microsoft have a better solution than this!

Note: exact duplicate of this question.

like image 568
Salim Fadhley Avatar asked Jan 28 '09 17:01

Salim Fadhley


People also ask

Can Python set environment variables?

With python code, environment variables can be set and manipulated. Setting the environment variable with code makes it more secure and it does not affect the running python script.

How do I permanently set an 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.


2 Answers

You might want to try Python Win32 Extensions, developed by Mark Hammond, which is included in the ActivePython (or can be installed separately). You can learn how to perform many Windows related tasks in Hammond's and Robinson's book.

Using PyWin32 to access windows COM objects, a Python program can use the Environment Property of the WScript.Shell object - a collection of environment variables.

like image 199
gimel Avatar answered Sep 30 '22 11:09

gimel


Windows sets Environment variables from values stored in the Registry for each process independently.

However, there is a tool in the Windows XP Service Pack 2 Support Tools named setx.exe that allows you to change global Environment variables from the command line.

like image 35
Powerlord Avatar answered Sep 30 '22 09:09

Powerlord