0

I try execute csh script(which creates or updates environment variables) from python but environment variables don't update after return to shell. Why ? How can I solve it ?

subprocess.call('script.csh',shell=True,executable="/bin/csh")
  • 1
    That isn't a Python issue. Parent processes don't inherit from their children. You can't even do it with a shell script, unless you `source` the script. – PM 2Ring Oct 12 '17 at 15:28
  • I use tcsh. What do you mean ? Can you give me workaround ? @PM 2Ring –  Oct 12 '17 at 15:29
  • 1
    The workaround is to have the shell script set the environment variables and then execute your Python script, rather than the way you're trying to do it now. Or, you can set them in Python using `os.environ`. – kindall Oct 12 '17 at 15:34
  • Sorry, but I don't understand your suggest. I execute csh script from python @kindall –  Oct 12 '17 at 15:51
  • He is saying you can't call a subprocess to do what you're doing. It would have to be a direct process as your environment variables can be passed to a subprocess, but subprocess environment variables are not passed back up to the parent process. For example, lets say you have a process called `parent_process` with env-var `"TEST"="MyTest"` and then you spawn your subprocess called `child_process` and overwrite `TEST` to be `"TEST"="YourTest"` when you check the `TEST` env-var back in your parent_process, it will still be `"TEST"="MyTest"`. – Billy Ferguson Oct 12 '17 at 16:00
  • Yes, I understand that you execute a csh script from Python. What I'm saying is that for the changes to the environment variables to be seen by Python, you have to do it the other way around. – kindall Oct 12 '17 at 16:28

1 Answers1

0

To set an environment variable in python, use

os.environ['YOUR_VARIABLE'] = "your_value"

Note that environment variables must be strings.

Explanation for why you cannot do what you want to do:

Environment variables are set in a per process memory space. When bash (or whatever shell have you) runs a program, it uses fork(), which inherits bash’s variables because it is a child process. What your trying to do is create a child process and have he parent inherit from the child, like @PM 2Ring said.

Steampunkery
  • 3,839
  • 2
  • 19
  • 28