How we can change linux environment variable in python?
35,585
Solution 1
There is no way to change the environment variables from a child process. And there is an exactly same question on SO.
Solution 2
There is a workaround to what you want to achieve. Assuming you use bash as your shell, you can write the changes to bash initialization files(I chose ~/.bashrc
):
#!/usr/bin/python
import os
os.system('bash -c \'echo "export a=100000" >> ~/.bashrc\'')
os.system('bash -c \'source ~/.bashrc\'')
You need to prepend bash -c
, since python uses sh
as the default shell.
Idea derived from a similar question on SO(different from the one falconer posted).
Related videos on Youtube
Author by
Mero
Updated on September 18, 2022Comments
-
Mero over 1 year
Let's say we are on a command line and we declare an environment variable:
export x=100
When i go to python and type :
os.environ['x'] = '100000'
If I came back to command line
x
stays100
. Is there any way to change this variable in python ? -
Avindra Goolcharan over 8 yearsThis is the correct answer. If you really need it, you'll have to start with a shell script, call python, and have your python communicate back to the shell script (there's multiple ways to do IPC, do some research and figure out what works for you).