Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 641
Roman Avatar asked Jul 15 '13 15:07

Roman


People also ask

How do you set a permanent environment variable in Python?

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.

How do I set environment variables permanently?

To make permanent changes to the environment variables for all new accounts, go to your /etc/skel files, such as . bashrc , and change the ones that are already there or enter the new ones. When you create new users, these /etc/skel files will be copied to the new user's home directory.

Can you set an environment variable in Python?

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.

Is environment variable permanent?

Set an Environment Variable in Linux PermanentlyIf you wish a variable to persist after you close the shell session, you need to set it as an environmental variable permanently. You can choose between setting it for the current user or all users. 6. Save and exit the file.


2 Answers

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

like image 124
rantanplan Avatar answered Sep 28 '22 02:09

rantanplan


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

like image 20
pelos Avatar answered Sep 28 '22 01:09

pelos