14
votes

Using os module I can get the values of the environment variables. For example:

os.environ['HOME']

However, I cannot set the environment variables:

os.environ['BLA'] = "FOO"

It works in the current session of the program but when I python program is finished, I do not see that it changed (or set) values of the environment variables. Is there a way to do it from Python?

4
For windows I can recommend a module to set variables through registry. Also has CLI app: github.com/beliaev-maksim/py_setenv this has good control on user/system level and does not have limit in length as setx - Beliaev Maksim

4 Answers

11
votes

If what you want is to make your environment variables persist accross sessions, you could

For unix

do what we do when in bash shell. Append you environment variables inside the ~/.bashrc.

import os
with open(os.path.expanduser("~/.bashrc"), "a") as outfile:
    # 'a' stands for "append"  
    outfile.write("export MYVAR=MYVALUE")

or for Windows:

setx /M MYVAR "MYVALUE"

in a *.bat that is in Startup in Program Files

0
votes

I am not sure. You can return the variable and set it that way. To do this print it.

(python program)

...
print foo

(bash)

set -- $(python test.py)
foo=$1
0
votes

if you want to do it and set them up forever into a user account you can use setx but if you want as global you can use setx /M but for that you might need elevation, (i am using windows as example, (for linux you can use export )

import subprocess
if os.name == 'posix':  # if is in linux
    exp = 'export hi2="youAsWell"'
if os.name == 'nt':  # if is in windows
    exp = 'setx hi2 "youAsWell"'
subprocess.Popen(exp, shell=True).wait()

after running that you can go to the environments and see how they been added into my user environments

enter image description here

0
votes

@rantanplan's answer is correct. For Unix however, if you wish to set multiple environment variables i suggest you add a \n at the end of outfile line as following:

outfile.write("export MYVAR=MYVALUE\n")

So the code looks like the following:

import os
with open(os.path.expanduser("~/.bashrc"), "a") as outfile:
    # 'a' stands for "append"  
    outfile.write("export MYVAR1=MYVALUE1\n")
    outfile.write("export MYVAR2=MYVALUE2\n")

This will prevent appending "export" word at the end of the value of the environment variable.