1

I wanted to set some environment variables in my bash / linux terminal using python script.

I tried:

import os;
os.environ['HOME_ROOT'] = '/home/aloha' 
os.putenv("HOME_ROOT", "/home/aloha")

but it wasn't setting the variables.

If I do as shown below from the shell script, it sets the required variables:

setenv HOME_ROOT /home/aloha

But I wanted to do the same using Python script. Am I making any mistake, or is it not possible to set env variables in bash/linux terminals from Python?

Please share your comments!

Metropolis
  • 2,018
  • 1
  • 19
  • 36
Vimo
  • 1,061
  • 3
  • 12
  • 22
  • 3
    A child process inherits its environment from its parent. You can't make the inheritance run backwards, no matter which language you use. To set env vars from a bash script you don't run it normally, you `source` it so it runs in the same context, not as a child. And you generaly use the `export` command so that the env vars will be inherited by child processes. – PM 2Ring Sep 18 '18 at 17:48
  • 1
    You are only adding variables to the mapping using `putenv`, you are not actually *setting* those variables – C.Nivs Sep 18 '18 at 17:49
  • Looking at how tools like `ssh-agent` work -- writing a snippet of shell script to stdout, such that a parent process can read and `eval` it -- may be informative. Note that using `eval` risks security vulnerabilities unless you trust the program doing that generation to use `pipes.quote()` or similar tools to escape values not to be parsed as code. – Charles Duffy Sep 18 '18 at 17:53
  • Can anyone post a basic example ? – Vimo Sep 18 '18 at 17:54
  • 1
    The linked duplicate *has* a basic example. Two, for that matter -- I just added another. – Charles Duffy Sep 18 '18 at 17:54
  • @CharlesDuffy But in that they are trying to call the python script in the bash script and set the env variables right? Is it possible to set the env variables in bash using only python script ? rather than calling the dependency ? – Vimo Sep 18 '18 at 17:57
  • You can't change the runtime environment of another process without its active assistance and involvement. You can change *your own* environment, and by extension that of your children, but not that of random other programs. – Charles Duffy Sep 18 '18 at 17:58
  • (well, can't in a portable way; there are awful, nonportable, fragile hacks that involve attaching with debuggers, but... well, those are awful hacks). – Charles Duffy Sep 18 '18 at 18:00
  • @CharlesDuffy: Thanks for the info. Will give a try with the example you had in the other post and see if that works for my requirement. – Vimo Sep 18 '18 at 18:02

0 Answers0