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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With