2

In my build (I'm using Linux) I need to call a Python script and set some env variables. I need these variables to be set even after I exit the script. I am able to set it using os.environ within the script but whenever I exit the script and try to see if the env variable is set from the terminal (echo $myenv) - I get nothing.

I am new to Python and did quite a bit googling to figure this out. However, I am not quite sure if it's possible. I tried using the subprocess:

subprocess.call('setenv myenv 4s3', shell=True)

Also tried using os.system:

os.system("setenv myenv 4s3")

So far, I didn't succeed.

tshepang
  • 12,111
  • 21
  • 91
  • 136
newbie
  • 4,639
  • 10
  • 32
  • 45
  • 1
    You must be new to Linux, too. There's no way to pass env settings back to the parent process, short of doing an **export VAR=$(my_script)**, in which case its output will be available to the other things you'll be running after your script terminated. – tink Dec 04 '13 at 21:39
  • http://stackoverflow.com/questions/496702/can-a-shell-script-set-environment-variables-of-the-calling-shell – PasteBT Dec 04 '13 at 21:39
  • just write to os.environ – Jan Matějka Dec 04 '13 at 21:42

2 Answers2

3

You cannot set environment variables from a child process and have them be visible in the parent process. Every process gets its own copy of the environment, and changes do not propagate upwards.

What you could do is have the Python script print the settings it wants to change and have the outside shell execute the appropriate commands.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

Maybe if you find some equivalent function like c vfork for Python.

When you vfork, both processes share memory space so, you might overwrite environment variables in parent process from child process.

Warning: vfork has many security issues, and therefore not recommended. Just use it if you are desperate.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60