Is it possible to set an environment variable from

2020-02-05 07:10发布

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?

2条回答
甜甜的少女心
2楼-- · 2020-02-05 07:53

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

查看更多
疯言疯语
3楼-- · 2020-02-05 07:53

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
查看更多
登录 后发表回答