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!

9
  • 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. Commented Sep 18, 2018 at 17:48
  • 1
    You are only adding variables to the mapping using putenv, you are not actually setting those variables Commented Sep 18, 2018 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. Commented Sep 18, 2018 at 17:53
  • Can anyone post a basic example ? Commented Sep 18, 2018 at 17:54
  • 1
    The linked duplicate has a basic example. Two, for that matter -- I just added another. Commented Sep 18, 2018 at 17:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.