简体   繁体   中英

Is it possible to set an environment variable from Python permanently?

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?

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

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

在此处输入图片说明

@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.

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

you can use py-setenv to do that job. It will access windows registry and do a change for you, install via python -m pip install py-setenv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM