0

I need to check if an environment variable exists in the system, and add it if not. I tried manually deleting the environment variable to test and used os.environ to add the variable:

import os
import site 
loct = site.getsitepackages()

if "OCTAVE_KERNEL_JSON" in os.environ:
    print("OCTAVE_KERNEL_JSON")
else:
    os.environ["OCTAVE_KERNEL_JSON"] = loct[1]+"\octave_kernel\kernel.json"

The code runs without error, but the expected environment variable was not created. Any suggestion?

Captain Jack Sparrow
  • 971
  • 1
  • 11
  • 28
Klien Menard
  • 103
  • 1
  • 1
  • 10
  • How are you measuring that it wasnt created, are you again checking `if "OCTAVE_KERNEL_JSON" in os.environ` immediatly in the code after you craeted it? – Chris Doyle Apr 28 '20 at 14:54
  • I checked it manually if it was created or not. I did not actually think of double checking it in the code though. – Klien Menard Apr 28 '20 at 14:58
  • @ChrisDoyle **UPDATE: I tried double checking it in the code and said it was already created but when I checked the environment variable manually, it wasn't there. – Klien Menard Apr 28 '20 at 15:01
  • 2
    Simply defining a variable in a program's local environment doesn't change it for the system. Bash uses the `export` command to make a variable available to future child processes. And you could have python rewrite a session script such as .bashrc, but otherwise that environment variable is only good for python and its child processes. – tdelaney Apr 28 '20 at 15:03
  • You could write a program `foo.py` that prints the bash export statement: `print('export OCTAVE_KERNEL_JSON=loct[1]+"\octave_kernel\kernel.json")` then exits. Now in your shell you can do `export \`python foo.py\``. (that's `python foo.py` surrounded by back ticks in case stackoverflow's markdown is ambiguous). – tdelaney Apr 28 '20 at 15:08
  • The environment isn't a two-way channel between a process and its parent. Children inherit a *copy* of the parent's environment, and that's it. – chepner Apr 28 '20 at 15:11
  • Hello everyone, thank you for the response I just want to say that I am using windows. Thanks! – Klien Menard Apr 28 '20 at 15:11
  • 1
    Even in windows, your python process will spawn in a new process with a copy of the system enviroment, any modifications you make to it will be applied only to that python process thats running. It wont change the gloabl system enviroment or affect any other programs copies of the system enviroment – Chris Doyle Apr 28 '20 at 15:12
  • Okay so its not possible to edit environment variables in the system using python? Is there a workaround to do it? – Klien Menard Apr 28 '20 at 15:12
  • 1
    its not possible with any language its the general system architecture that child processes cannot change the enviroment of its parent processes or the system, otherwise a lot of bad things could be done or occur – Chris Doyle Apr 28 '20 at 15:16

0 Answers0