I'm trying to set a Windows environment variable using Python.
It seems that, contrary to the docs, os.environ can get environment variables but cannot set them. Try running these in a Windows Command Prompt:
This works:
python -c "import os; print(os.environ['PATH'])"
This does not:
python -c "import os; os.environ['FOO'] = 'BAR'"
Try typing set
in the Command Prompt. The environment variable FOO does not exist.
How can I set a permanent Windows environment variable from Python?
os.environ[...] = ...
sets the environment variable only for the duration of the python process (or its child processes).
It is not easily (i.e. without employing OS-specific tools) possible and surely not advisable to set the variable for the shell from which you run Python. See aumo's comment for alternative and somewhat obscure approaches to the problem.
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